不使用 atoi() 或 stoi() 的 C++ 字符串到 int
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19311641/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C++ string to int without using atoi() or stoi()
提问by user2661167
Hi I am new to C++ and trying to do an assignment where we read a lot of data from a txt file in the format of
嗨,我是 C++ 的新手,并试图做一项作业,我们从 txt 文件中读取大量数据,格式为
surname,initial,number1,number2
I asked for help before an someone suggested reading the 2 values as string then use stoi() or atoi() to convert to int. This works great, except I need to use this parameter "-std=c++11" for compiling or it will return an error. This is not a problem on my own computer which will handle "-std=c++11", but unfortunately for me the machines which I have to present my program on does not have this option.
在有人建议将 2 个值作为字符串读取然后使用 stoi() 或 atoi() 转换为 int 之前,我寻求帮助。这很好用,除非我需要使用这个参数“-std=c++11”来编译否则它会返回一个错误。这在我自己的将处理“-std=c++11”的计算机上不是问题,但不幸的是,我必须在其上展示我的程序的计算机没有此选项。
If there another way which I can convert string to int that doesn't use stoi or atoi?
如果有另一种方法可以将字符串转换为不使用 stoi 或 atoi 的 int?
Here is my code so far.
到目前为止,这是我的代码。
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);
}
回答by wangyang
I think you can write your own stoi function. here is my code, I have tested it, it's very simple.
我认为您可以编写自己的 stoi 函数。这是我的代码,我已经测试过了,非常简单。
long stoi(const char *s)
{
long i;
i = 0;
while(*s >= '0' && *s <= '9')
{
i = i * 10 + (*s - '0');
s++;
}
return i;
}
回答by Mateusz Ko?odziejski
You are already using stringstream, which gives you such "feature".
您已经在使用 stringstream,它为您提供了这样的“功能”。
void func()
{
std::string strnum1("1");
std::string strnum2("2");
int number1;
int number2;
std::stringstream convert;
convert << strnum1;
convert >> number1;
convert.str(""); // clear the stringstream
convert.clear(); // clear the state flags for another conversion
convert << strnum2;
convert >> number2;
}