c++在长字符串中将字符串转换为整数

C++ converting a string to integers in a lengthy string

本文关键字:字符串 转换 整数 c++      更新时间:2023-10-16

我正在写一个程序,我将得到一个字符串,如:

5、6、10

,我编写了一个程序,将数字5 6 10(忽略逗号)放入一个向量中。我的程序唯一的问题是,如果我做了像

这样的事情

5、6 f

就会把f变成0。而我希望程序在看到0 1 2 3 4 5 6 7 8 9

之外的任何内容时报告错误

我如何修复我的程序来做到这一点?下面是我的代码:

#include <cstdlib>
#include <iostream>
#include <string>
#include <vector>
using namespace std;

int main()
{
    string str, temp;
    cout << "enter string: n";
    getline (cin, str);
    vector<int> vec;
    int num;
    for (int j=0; j < str.size(); j++)
{
    int num2= str.size()-1;
    if (isdigit(str[j]))
    {
        temp+= str[j];
        num = atoi(temp.c_str());
        if (num2 ==j)  //if program is at end of string and it's still a number
            vec.push_back(num); //push back value
    }
    else if (str[j] == ',')
    {
        num = atoi(temp.c_str());
        temp.clear();
        vec.push_back(num);
    }
    else
    {
        cout << "errorn";
        temp.clear();
    }
}
    for (int k=0; k < vec.size(); k++)
        cout << vec[k] <<endl;
}

atoi不安全,用strtol代替。

摘自atoi的文档:

如果str不指向有效的C-string,或者转换后的值是否超出了可由int表示的值的范围未定义的行为。

的例子:

// ...
char *end;
long int res = strtol(str, &end, 10);
if (str == eptr) {
    throw std::invalid_argument("invalid strtol argument");
}
if (errno == ERANGE) {
    throw std::out_of_range("strtol argument out of range");
} 

更新:你的代码应该看起来像这样:

char *iter = str.c_str(); // your str
char *end;
while ( *iter ) {
    int res = strtol(iter, &end, 10);
    // not a number, skip it and continue with the next one
    if (iter == end) {
        iter++;
        cout << "error: " << *iter << endl;
        continue;
    }
    // handle the out-of-range error
    if (errno == ERANGE) {
        cout << "overflow: " << string(iter, end) << endl;
    } else {
        // number is valid
        vec.push_back(res);
    }
    // continue iterating, skip char at (*end) since it's not an integer
    iter = end + 1;
}

警告:之前的代码没有编译或测试