use*_*167 4 c++ string int type-conversion atoi
嗨,我是C ++的新手,正在尝试做一个作业,我们从txt文件中读取许多数据,格式为
surname,initial,number1,number2
Run Code Online (Sandbox Code Playgroud)
在有人建议将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);
}
Run Code Online (Sandbox Code Playgroud)
小智 5
我认为您可以编写自己的stoi函数。这是我的代码,我已经测试过了,非常简单。
long stoi(const char *s)
{
long i;
i = 0;
while(*s >= '0' && *s <= '9')
{
i = i * 10 + (*s - '0');
s++;
}
return i;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
23066 次 |
| 最近记录: |