【问题标题】:Adding up Integer Values within a String将字符串中的整数值相加
【发布时间】:2019-08-12 22:22:08
【问题描述】:

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

“编写一个程序,要求用户输入一系列单位数字,没有任何分隔。将输入读取为 c 字符串或字符串对象。程序应显示所有单位数字字符串。例如,如果用户输入 2514,程序应该显示 12,即 (2+5+1+4)。程序还应该显示字符串中的最高位和最低位。"

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

#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 != "\0")
        {
           sum = integers[i]++;
        }
    }

    //Outputting Sum:
    cout << sum;

    return 0;
}

【问题讨论】:

  • 您必须将字符串的每个字符转换为数字,然后使用该数字进行加法运算。我怀疑弄清楚如何做到这一点是你的任务目的的一部分,这意味着你应该尝试自己解决这个问题。
  • 你知道用户每次输入要多长时间吗?还是您没有提供这些信息?

标签: c++ string c-strings


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    你可以这样使用:

    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++ 中是未定义的行为,可能包含垃圾,从 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 == "\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 的整数值

    【讨论】:

    • 不要将此视为批评,但 OP 显然正在遵循一些旨在教授的家庭作业任务,而不是提供代码(没有任何解释 - 在任何情况下都没有帮助,)尝试未来提供一些指导并让他们弄清楚 - 他们很可能会达到任务的目标。
    • @Nim,我很重视您的意见,这是向他解释发生了什么的好方法吗?他的代码中有很多错误,我试图尽可能地解释每一个错误。
    • @Gox - 解释很好,但是,你应该更谨慎地放弃代码 - 这里的原则是学习者必须学习,这是学习过程的一部分还在寻找他们不知道的概念的资源,如果您只是提供代码(即使有解释),诱惑就是简单地复制代码并将其提交(我并不是说这是这个特定的 OP 会做的事情,但它就在那里..) 所以,下一次,只需解释某人哪里出了问题,并提供一些关于他们可以查看的指导。
    【解决方案3】:

    在上面各位的帮助下,我对其进行了编辑,现在它的工作方式如下:

    #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] != '\0')
            { 
                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;
    }
    

    【讨论】:

    • 这太过分了:(每个char都有十进制值。char '0'有十进制值48,char '1'有十进制值49char '2'是50等等。那么如果你在字符串中输入5会发生什么?内存包含什么十进制值?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-05
    相关资源
    最近更新 更多