//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/