ran*_*guy 3 c++ string file-io
我想解析一个逐行描述一组数据的文件.每个数据由3或4个参数组成:int int float(optional)string.
我打开文件ifstream inFile并在while循环中使用它
while (inFile) {
string line;
getline(inFile,line);
istringstream iss(line);
char strInput[256];
iss >> strInput;
int i = atoi(strInput);
iss >> strInput;
int j = atoi(strInput);
iss >> strInput;
float k = atoi(strInput);
iss >> strInput;
cout << i << j << k << strInput << endl;*/
}
Run Code Online (Sandbox Code Playgroud)
问题是最后一个参数是可选的,所以当它不存在时我可能会遇到错误.如何提前检查每个数据的参数数量?
此外,
string line;
getline(inFile,line);
istringstream iss(line);
Run Code Online (Sandbox Code Playgroud)
看起来有点红,我怎么能简单地说呢?
在这种情况下使用惯用法,它变得更加简单:
for (std::string line; getline(inFile, line); ) {
std::istringstream iss(line);
int i;
int j;
float k;
if (!(iss >> i >> j)) {
//Failed to extract the required elements
//This is an error
}
if (!(iss >> k)) {
//Failed to extract the optional element
//This is not an error -- you just don't have a third parameter
}
}
Run Code Online (Sandbox Code Playgroud)
顺便说一下,atoi除非0你正在解析的字符串不是一个可能的值,否则会有一些非常不受欢迎的歧义.由于atoi返回0,当它的错误,你可以不知道如果返回值0是一个字符串的成功解析了一个数0,或者,除非你做原始的字符串一些相当费力的检查这是一个错误,你已经解析它.
尽量采用流,但在你需要回落到情况atoi类型的功能,顺应strtoX系列函数(strtoi,strtol,strtof等).或者,更好的是,如果您使用的是C++ 11,请使用stoX函数族.
| 归档时间: |
|
| 查看次数: |
981 次 |
| 最近记录: |