C++ 如何在C++;?

C++ 如何在C++;?,c++,numbers,digits,C++,Numbers,Digits,我在想办法从一个整数中分别得到5位数字 cin >> option; // Option to enter a number(don't worry about this) if (option == 1) // The option(don't worry) { cout << " enter 5 digit key 0 to 9 \n"; readin(key); // The input number that needs th

我在想办法从一个整数中分别得到5位数字

cin >> option;      // Option to enter a number(don't worry about this)
if (option == 1)    // The option(don't worry)
{
    cout << " enter 5 digit key 0 to 9 \n";
    readin(key);    // The input number that needs the digits to be separated
}
cin>>选项;//输入数字的选项(不用担心)
if(option==1)//选项(不要担心)
{
不能像这样:

// handle negative values
key = ABS(key);

while(key > 0)
{
    // get the digit in the one's place (example: 12345 % 10 is 5)
    int digit = key % 10;

    // remove the digit in the one's place
    key /= 10;
}

为什么不单独读取每个输入并单独处理它们

i、 e


cout您可以使用以下代码段,它将在
循环时按相反顺序分隔数字

int i;
cin >> i;

while (i%10 != 0) 
{
  cout << i%10 << endl;
  i = i/10;
}
inti;
cin>>i;
而(i%10!=0)
{

coutwhile循环方法只处理没有零的数字。

\include
#include <iostream>
#include <string>
using namespace std;

int main()
{
  string str;
  cin >> str;

  size_t len = str.size();
  len = len > 5 ? 5 : len;

  for (size_t i=0; i<len; ++i)
  {
    cout << "digit " << i << " is: " << (str[i] - '0') << endl;
  }

  return 0;
}
#包括 使用名称空间std; int main() { 字符串str; cin>>str; 大小长度=长度大小(); len=len>5?5:len;
对于(size_t i=0;i这里有一个提示-查看.1,“做点什么”很可能从
str[i]-=“0”;
+1开始。您还可以在循环之前添加一个负数快速检查。如果负数,则输出或存储
-
,然后在进入循环之前将其设置为正数。
#include <iostream>
#include <string>
using namespace std;

int main()
{
  string str;
  cin >> str;

  size_t len = str.size();
  len = len > 5 ? 5 : len;

  for (size_t i=0; i<len; ++i)
  {
    cout << "digit " << i << " is: " << (str[i] - '0') << endl;
  }

  return 0;
}