提问者:小点点

如何在C++中拆分数字


我知道在堆栈溢出上也有类似的问题。 我已经查过了。 这里有两点:

>

  • 数字将是用户的输入,因此我不知道数字实际上可能包含多少位数字

    我不想直接打印数字,我需要对每一个数字做一些进一步的处理,所以我需要一种方法来保存或分配每一个数字。 例如,如果用户输入1027,我需要返回1,0,2,7,而不是打印。 我的问题就从这里开始。 如果可以打印的话,我会这样写:

    int x;
    cin>>x;
    while(x != 0)
    {
       cout<<x%10<<endl;
       x/=10;
    }
    

    如有任何提示或帮助,我们将事先表示感谢。


  • 共3个答案

    匿名用户

    使用std::string:

    std::string input;
    std::cin >> input;
    

    现在输入[i]第i位。 Input.Size()是位数。

    匿名用户

    这取决于你需要它的顺序。 如果您需要最低有效数字(最右)到最高有效数字(最左),那么您的解决方案就差不多实现了

    int x = ...
    while(x != 0)
    {
       int current = x % 10; // get rightmost digit
       x /= 10;
       // process 'current', or store in a container for later processing
    }
    

    如果您需要最高有效(最左)到最低有效(最右),那么您可以递归地这样做:

    void for_each_digit(int input)
    {
      // recursive base case
      if (input == 0) { return; };    
    
      int current = input % 10
      for_each_digit(input / 10); // recurse *first*, then process
      // process 'current', add to container, etc
    }
    
    // ...
    
    
    int x = ...
    for_each_digit(x);
    

    编辑:我显然漏掉了关于返回数字序列的部分。

    两种方法都有效。 如果你从右到左,你将需要首先反转容器。 如果使用递归,则需要将每个值追加到容器中。

    匿名用户

    你可以用矢量。 它可以采取可变长度的输入。 你不必事先申报尺寸。 了解有关vector的更多信息,请访问:vector

    #include<iostream>
    #include<vector>
    #include <algorithm> // std::reverse
    using namespace std;
    
    int main(void)
    {
        vector<int>digits;
        int x;
        cin >> x;
    
        while(x)
        {
            digits.push_back(x % 10);
            x = x / 10;
        }
    
        // reversing the order of the elements inside vector "digits" as they are collected from last to first and we want them from first to last.
        reverse(digits.begin(), digits.end());
        
        // Now the vector "digits" contains the digits of the given number. You can access the elements of a vector using their indices in the same way you access the elements of an array.
        for(int i = 0; i < digits.size(); i++) cout << digits[i] << " ";
    
        return 0;
    }
    

    相关问题


    MySQL Query : SELECT * FROM v9_ask_question WHERE 1=1 AND question regexp '(何在|c++|中|拆分|数字)' ORDER BY qid DESC LIMIT 20
    MySQL Error : Got error 'repetition-operator operand invalid' from regexp
    MySQL Errno : 1139
    Message : Got error 'repetition-operator operand invalid' from regexp
    Need Help?