【发布时间】:2013-10-19 03:36:17
【问题描述】:
您好,我是 C++ 新手,正在尝试执行一项任务,我们从 txt 文件中读取大量数据,格式为
surname,initial,number1,number2
在有人建议将 2 个值读取为字符串然后使用 stoi() 或 atoi() 转换为 int 之前,我寻求帮助。这很好用,除了我需要使用这个参数“-std=c++11”进行编译,否则会返回错误。这在我自己的计算机上可以处理“-std=c++11”不是问题,但不幸的是,我必须在其上展示我的程序的机器没有这个选项。
如果有另一种方法可以将字符串转换为不使用 stoi 或 atoi 的 int?
这是我目前的代码。
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。 -
当你想要的是
istringstream时,这种使用stringstream的狂热是什么? (我经常看到,我不明白为什么有人会这样做。) -
另外,对于这种格式,我会使用
boost::split之类的东西,而不是istringstream(这仍然存在转换为int的问题)。
标签: c++ string int type-conversion atoi