【问题标题】:How can I perform this code in C and C++? [closed]如何在 C 和 C++ 中执行此代码? [关闭]
【发布时间】:2022-01-13 05:52:12
【问题描述】:

我是 C 和 C++ 的新手,我想要这段代码,在 python 中是这样的:

num = ""
while current_char.isdigit():
    num += current_char

我希望这段代码在 C 和 C++ 中执行,我知道我可以使用名为 isdigit() 的内置函数检查 char 是否为数字,但我不知道如何执行这段代码,任何非常感谢您的帮助...

【问题讨论】:

  • C 和 C++ 是两种不同的语言,每种语言的答案都会有所不同。在 C++ 中,std::string 的重载为 operator+=,该列表中的 #2,在右侧接受 char

标签: python c++ c string while-loop


【解决方案1】:

我想会是这样的

std::string num = "";
while isdigit(current_char){
    num += current_char;
}

【讨论】:

    【解决方案2】:

    isdigit() 函数的原型在 <ctype.h> 文件中定义,如果 char 值为数字,则返回 0 以外的值。

    #include <stdio.h>
    #include <ctype.h>
    
    int main()
    {
        int number = 0;
        char current_char[] = {'1', '2', '3', 'a', 'b', 'c'};
    
        /* Scan all elements of character array */
        for(int i = 0 ; current_char[i] != '\0' ; ++i)
        {
            /* If the character is a number, isdigit() returns a value other than 0. */
            if(isdigit(current_char[i]))
            {
                printf("%c\t", current_char[i]);
    
                /* Convert char value to int value and sum the result */
                number += current_char[i] - '0';
            }
        }
    
        printf("\nTotal: %d", number);
    
        return 0;
    }
    

    该程序产生以下输出:

    1   2   3
    Total: 6
    

    【讨论】:

      【解决方案3】:

      这就是你在 c++ 中检查数字的方式

      #include<stdio.h>
      #include<ctype.h>
      int main() {
         char first = 'q';
         char second = '7';
         if(isdigit(first)) {
             printf("The character is a digit\n");
         }
         else {
             printf("The character is not a digit\n");
         } 
         if(isdigit(second)) {
             printf("The character is a digit\n");
         }
         else {
             printf("The character is not a digit");
         }
         return 0;
      }
      

      【讨论】:

      • C++ 对此没有什么特别之处。这是 C 代码。它可以使用 C++ 编译器进行编译,但这不会使其成为 C++。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-12
      • 1970-01-01
      • 2011-11-24
      • 1970-01-01
      相关资源
      最近更新 更多