C++将字符串转换为int

标签 c++ string int

//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++将字符串转换为int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8014387/

相关文章:

c++ - 寻找字符串实现中的最大回文

c++ - 如何显示常量字符指针的地址

java - 如何使用流从 double 组中过滤掉非整数值?

java - Java 将 int 转换为 double

c++ - 使用 boost::iterator_facade<> 为迭代器返回 ref 但为 const_iterator 返回 const_ref?

php - 字符串中的无效 JSON 转义序列

java - 如何从n组不同大小的数字中选择n个数字?

c - 使用 getchar() 获取未知长度的整数

c++ - 为vector的删除函数实现一个拷贝构造函数

c++ - 在 C++ 中为结构( union )创建构造函数