为什么我的代码对于 10 5 3 的输入没有显示任何内容。它适用于 1 到 9 之前的所有内容,但是每当它达到 10 或大于 10 时,就不会显示任何输出。我也尝试为此使用 atoi() 但此行中有错误 int x = str[j] - '0' 。请帮助我。
#include<iostream>
#include<string>
#include<cstdlib>
using namespace std;
int main()
{
int n, sum = 1, num = 0;
string str;
cin >> n;
for(int i = 0; i <= n; i++) {
getline(cin, str);
for(int j = 0; j < str.length(); j++) {
if(str[j] != ' ') {
int x = str[j] - '0'; // Here is the problem even I use atoi() but error
sum *= x;
num = sum;
}
}
if(num != 0) {
cout << num << endl;
num = 0;
sum = 1;
}
}
}
最佳答案
从您的帖子中不清楚为什么您有两个变量 num
和 sum
。这似乎是多余的。
假设您只需要 num
,替换这些行
sum *= x;
num = sum;
通过
num = (10*num + x);
得到正确的数字。
此外,当您遇到空格时,您需要将num
重置为0
。否则,输入 10 8
将被视为 108
。
for(int j = 0; j < str.length(); j++) {
if(str[j] != ' ') {
num = (10*num + x);
} else {
// Use num and then reset it 0
// ...
num = 0;
}
}
关于c++ - 无法在循环中的 C++ 中将字符转换为整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32363496/