c++在长字符串中将字符串转换为整数
C++ converting a string to integers in a lengthy string
我正在写一个程序,我将得到一个字符串,如:
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;
}
警告:之前的代码没有编译或测试
相关文章:
- 如何将包含epoch时间的十六进制字符串转换为time_t
- 当字符串存储在变量中时,如何将字符串转换为wchar_t
- 如何将这个std::字符串转换为std::基本字符串
- 如何正确将字符串转换为标准::时间::system_clock::time_point?
- 如何在C++中将十六进制字符串转换为文本数据
- 需要帮助在 c++ 中将字符串转换为字符 ----错误 "const char *" 类型的值不能用于初始化 "char" 类型的实体
- 如何从字符串转换为双精度*
- C++:如何将 unix 时间的字符串转换为 *tm?(使用时间错误:"cannot convert 'String' to 'tm*' ")
- 如何在C++中将 Python 字符串转换为其转义版本?
- 如何在 C++11 中将标准::字符串转换为标准::u32字符串?
- 如何将整数字符串转换为整数的二维向量?
- 使用 "stringstream " 将字符串转换为整数
- 将字符串转换为浮点数或整数,而无需使用内置函数(如 atoi 或 atof)
- 将文件复制到自定义位置,存在字符串转换问题
- 将ANSI C字符串转换为UNICODE
- 如何将节点 V8 字符串转换为 C++ 字符串
- 在C++中将字符串转换为双精度,而无需科学记数法
- 使用从文件(stod、strtod、atof)中提取的数据C++从字符串转换为双精度.csv
- 如何在C++中将字符串转换为双精度?
- 将字符串转换为无符号字符数组/字节数组