你好,我是C++的新手,正在尝试完成一项任务,在这个任务中我们需要从一个格式为txt的文件中读取大量数据。
surname,initial,number1,number2
我曾经寻求帮助,有人建议将2个值作为字符串读取,然后使用stoi()或atoi()将其转换为整数。这很有效,但我需要使用编译参数“-std=c ++ 11”,否则会返回错误。这在我的电脑上不是问题,因为我的电脑可以处理“-std=c ++ 11”,但不幸的是,我必须在其他机器上演示程序,而这些机器没有这个选项。
是否有其他方法可以将字符串转换为整数而不使用stoi或atoi?
以下是我的代码。
while (getline(inputFile, line))
{
stringstream linestream(line);
getline(linestream, Surname, ',');
getline(linestream, Initial, ',');
getline(linestream, strnum1, ',');
getline(linestream, strnum2, ',');
number1 = stoi(strnum1);
number2 = stoi(strnum2);
dosomethingwith(Surname, Initial, number1, number2);
}
atoi
使用-std=c++11
。但我会避免使用atoi
,因为它不允许任何错误检查。更好的解决方案是strtoi
。 - James Kanzestringstream
的狂热,其实应该用istringstream
才对啊?(我经常看到这种情况,但我不明白为什么有人会这样做。) - James Kanzeboost::split
的东西,而不是istringstream
(这仍然存在将其转换为“int”的问题)。 - James Kanze