在字符串中添加整数值

Adding up Integer Values within a String

我无法解决我的一个家庭作业问题。

"Write a program that asks the user to enter a series of single-digit numbers with nothing separating them. Read the input as a c-string or a string object. The program should display all the single-digit numbers in the string. For example, if the user enters 2514, the program should display 12, which is (2+5+1+4). The program should also display the highest and lowest digits in the string."

我遇到的问题是弄清楚如何将字符串中的整数相加。我的代码在下面,感谢任何帮助,谢谢!。

#include <iostream>
#include <cstring>
using namespace std;

int main()
{
    //Declaring Variables & Character Array:
    int size;
    int sum;
    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;

    //Adding up Contents Within String:
    for(int i = 0; i < size; i++)
    {
        if(integers[i] > 0 && integers[i] < 9 && integers != "[=10=]")
        {
           sum = integers[i]++;
        }
    }

    //Outputting Sum:
    cout << sum;

    return 0;
}

所以您的方法存在几个问题,请考虑以下提示:

  1. 不要读入 char 数组,而是从 cin 读入 std::string
  2. 当您迭代 for 循环中的字符串字符时,它们不是数字,而是 ascii 字符。您需要弄清楚如何将 '0' 翻译成 0(提示,ascii 字符也有数值,或许可以调查一下。)
  3. sum = integers[i]++; 这不是你 求和 数字的方式..

你可以这样使用:

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 != '[=11=]') {
    sum = integers[i] - `0`;
}

你也有问题:

integers != "[=12=]"

应该是:

integers[i] != '[=13=]'

"" 是字符串的表示,即使您有 "" 它也是一个空字符串,但其中包含 [=27=]。在上面的例子中,“\0”包含“[=87=][=87=]”。所以基本上你想要的是将单个字符与 [=27=] 进行比较,而你将字符串与 [=29=][=29=].

进行比较

又一个错误:

int size;
...
char integers[size];
...
cin >> integers; // SEGFAULT HERE
size = strlen(integers); 

未初始化的变量在 C++ 中是未定义的行为,可能包含垃圾,从 0MAX_INT。如果 size0,您可能会得到 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 == "[=16=]" is comparing entire string with stirng which contains "[=16=]":s
        // < and > shoudl be <= nad >= to include 0 and 9                                                                                                                                                                                
        if(integers[i] >= '0' && integers[i] <= '9' && integers[i] != '[=16=]')
        {
           // sum = integers[i]++; is incrementing character at integer[i]` not `sum`
           sum += integers[i] - '0';
        }
    }

    //Outputting Sum:
    cout << sum;

    return 0;
}

Hah 刚刚意识到你有另一个错误:strlen() returns 整数的长度可以说 string s="ABCD" 给定 strlen(s) 将 return 4,并且稍后在 for() 循环中,循环从 0 到 4,但不包括 4,因为 s[0] = 'A's[1] = 'B's[2] = 'c's[3] = 'D'.

好的,进一步解释一下,字符也有数字值:

如果您看到所有字符都有十进制值:这里是上面的 ascii table 中 0 - 9 的简短 table 个字符:

 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

的整数值

在上面你们的帮助下,我对其进行了编辑,现在它可以像这样工作了:

#include <iostream>
#include <cstring>
using namespace std;

int main()
{
    //Declaring Variables & Character Array:
    int size;
    char integers[size];
    int sum;

    //Small and Large Numbers:
    int small = 9;
    int large = 0;

    //Gathering Integers:
    cout << "Please enter a series of integers with nothing between them.";
    cin >> integers;

    //Gathering Size of String:
    size = strlen(integers) + 1;

    for(int i = 0; i < size; i++)
    {
        if(integers[i] >= '0' && integers[i] <= '9' && integers[i] != '[=10=]')
        { 
            if(integers[i] == '0')
                sum += 0;
            if(integers[i] == '1')
                sum += 1;
            if(integers[i] == '2')
                sum += 2;
            if(integers[i] == '3')
                sum += 3;
            if(integers[i] == '4')
                sum += 4;
            if(integers[i] == '5')
                sum += 5;
            if(integers[i] == '6')
                sum += 6;
            if(integers[i] == '7')
                sum += 7;
            if(integers[i] == '8')
                sum += 8;
            if(integers[i] == '9')
                sum += 9;
        }
    }

    cout << sum << endl;


    return 0;
}