//sLine is the string
for(int l = 0; l < sLine.length(); l++)
{
    string sNumber;
    if(sLine[l] == '-')
    {
        sNumber.push_back(sLine[l]);
        sNumber.push_back(sLine[l + 1]);
        l++;
    }
    else if(sLine[l] != '\t')
    {
        sNumber.push_back(sLine[l]);
    }
    const char* testing = sNumber.c_str();
    int num = atoi(testing);
    cout << num;
}


我有这个for循环,它检查字符串的每个字符并将该字符串中的每个数字转换为int。但是由于某种原因,atoi函数执行了两次,所以当我退出它时,由于某种原因它会显示两次...为什么呢?

例:
输入
3 3 -3 9 5
-8 -2 9 7 1
-7 8 4 4 -8
-9 -9 -1 -4 -8

输出值
3030-309050
-80-20907010
-70804040-80
-90-90-10-40-80

最佳答案

它对所有无法识别的字符都显示为零,因为当给定非数字字符串(例如空格!)时,atoi返回0

但是,您要执行的操作非常简单:

std::stringstream ss(sLine);
int num;
while(ss >> num) {
    cout << num;
}

关于c++ - C++将字符串转换为int,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8014387/

10-11 17:49