你可以这样使用:
std::string integers;
//Gathering Integers:
cout << "Please enter a series of integers with nothing between them.";
cin >> integers;
int sum = 0;
for (char c : integers)
if (c >= '0' && c <= '9')
sum += c - '0';
为了解释上面代码的作用,我相信前几行是显而易见的,我将跳到for() 循环。这是 C++ 中使用的 foreach 循环的形式。它从字符串中逐个字符地抓取并将其存储在变量中(在本例中为c),并且在循环内我们可以正常检查c 是否为数字0 到9 的ASCII 表示。随后将ASCII 表示转换为integer (c - '0')。
您的方法是将整数与 ASCII 字符进行比较,您可以试试这个:
if(integers[i] >= '0' && integers[i] =< '9' && integers != '\0') {
sum = integers[i] - `0`;
}
你也有问题:
integers != "\0"
应该是:
integers[i] != '\0'
"" 是字符串的表示形式,即使您有"",它也是一个空字符串,但其中包含\0。在上述情况下,“\0”包含“\0\0”。所以基本上你想要的是将单个字符与\0 进行比较,而你将字符串与\0\0 进行比较。
又一个错误:
int size;
...
char integers[size];
...
cin >> integers; // SEGFAULT HERE
size = strlen(integers);
未初始化的变量在 C++ 中是未定义的行为,可能包含垃圾,从 0 到 MAX_INT。如果size 是0,您可能会得到segfault,然后您尝试在integers 中输入多个0 字符。在您到达size = strlen() 之前,您就会出现段错误。
另一个未初始化的变量:
int size;
在修复了上面提到的所有错误后,我实际上得到了 432552 作为我的程序输出。
这是你的调试代码:
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
//Declaring Variables & Character Array:
int size = 100; // UNINITIALIZED VARIABLE
int sum = 0; // UNINITIALIZED VARIABLE
char integers[size];
//Gathering Integers:
cout << "Please enter a series of integers with nothing between them.";
cin >> integers;
//Gathering Size of String:
size = strlen(integers); // +1 ??? why
//Adding up Contents Within String:
for(int i = 0; i < size; i++)
{
// integers[i] >= 0 is comparing char to int
// integers[i] <= 9 is comparing char to int
// ingegers == "\0" is comparing entire string with stirng which contains "\0":s
// < and > shoudl be <= nad >= to include 0 and 9
if(integers[i] >= '0' && integers[i] <= '9' && integers[i] != '\0')
{
// sum = integers[i]++; is incrementing character at integer[i]` not `sum`
sum += integers[i] - '0';
}
}
//Outputting Sum:
cout << sum;
return 0;
}
哈哈,刚刚意识到您遇到的另一个错误:strlen() 返回整数长度让我们说string s="ABCD" 给定strlen(s) 将返回 4,稍后在for() 循环中循环从 0 到 4 但不包括4 自 s[0] = 'A'、s[1] = 'B'、s[2] = 'c' 和 s[3] = 'D'。
好的,进一步解释一下,字符也有数字值:
如果您看到所有字符都有十进制值:这是上面 ascii 表中的字符短表0 - 9:
Character | Decimal Value
----------+--------------
0 | 48
1 | 49
2 | 50
3 | 51
4 | 52
5 | 53
6 | 54
7 | 55
8 | 56
9 | 57
所以这样做:
integers[i] - '0'
基本上就像在说
integers[i] - 48
如果integer[i] 是8,它将保存56 的十进制值。所以56 - 48 会给出8 的整数值