我很困惑如何解析多个分隔符使用getline和strtok在c ++ [英] I am very confused on how to parse multiple delimiters using getline and strtok in c++
问题描述
我的代码发布在下面。
My code is posted below. I want to be able to parse using the delimiters " ()," and convert the strings into integers in cpp.
while(getline(fin, line))
{
x = atoi((strtok(line.c_str(),'(,)'));
xx = atoi((strtok(NULL,"(),"));
xxx = atoi((strtok(NULL,"(),")));
cout << x << " " << xx << " " << xxx << "\n";
}
但由于某种原因,我得到以下错误
but for some reason I get the following errors
GraphTest.cpp:134:错误:从'const char *'到'char *'的无效转换
GraphTest.cpp:134: error: invalid conversion from ‘const char*’ to ‘char*’
GraphTest.cpp:134:error:初始化'char * strtok(char *,const char *)'的参数1
GraphTest.cpp:134: error: initializing argument 1 of ‘char* strtok(char*, const char*)’
.c_str应该将我的字符串转换为ac类型的字符串,允许我使用atoi和strtok函数。我很困惑,并会感谢任何帮助。
The .c_str should convert my string into a c type string allowing me to use the atoi and strtok functions. I am very confused and would appreciate any help.
推荐答案
它不会编译,因为 c_str()
返回 const char *
,它应该是一个不可修改的内部 string
缓冲区的常量指针。另一方面, strtok()
接受 char *
,因为它修改其输入字符串。
It doesn't compile because c_str()
returns a const char*
, it's supposed to be a constant pointer to not modifiable internal string
buffer. On the other hand strtok()
accepts a char*
because it modifies its input string.
现在你有两个选择:从 strtok()
获取一个C字符串,或者将所有的内容重写为C ++。
Now you have two options: get a C string usable from strtok()
or rewrite everything to be C++.
从C ++字符串中创建一个新的可修改的C字符串:
Create a new modifiable C string from your C++ string:
char* modifiableLine = strdup(line.c_str());
x = atoi((strtok(modifiableLine, "(,)"));
// Other processing
free(modifiableLine);
如果你必须保持一个大函数/类更好的解决方案是使用C ++标准库提供的(如果C ++ 11),还要删除 atoi()
C函数让我们先写一个帮助函数: p>
You can do it if you have to keep a big amount of C code wrapped inside a C++ function/class. A better solution is to use what C++ Standard Library offers (also dropping atoi()
C function if C++ 11). Let's first write an helper function:
int readNextInt(istringstream& is, const string& delimiters) {
string token;
if (getline(is, token, delimiters))
return stoi(token);
return 0; // End of stream?
}
使用像这样:
istringstream is(line)
x = readNextInt(is, "(),");
xx = readNextInt(is, "(),");
xxx = readNextInt(is, "(),");
请注意,标准C ++函数 getline / code>不接受分隔符参数的
字符串
,但只有一个 char
编写自己的重载版本。看看这篇文章是否有好的可能实现(你也可以简单地替换 getline )之后的
是>>标记
示例)。
Please note that standard C++ function getline()
doesn't accept a string
for delimiters parameter but a single char
only then you have to write your own overloaded version. Take a look to this post for good and nice possible implementation (you may also simply replace getline()
with is >> token
after is.imbue()
, see given example).
好吧,如果你已经使用Boost,那么你可以使用 boost :: tokenizer
。
Well...if you're already using Boost then you may simply use boost::tokenizer
.
这篇关于我很困惑如何解析多个分隔符使用getline和strtok在c ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!