質問

私は、整数とは別に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
}

上記のコードは数字を入力するだけですが、何らかの形で数字を分離したいのですが...

役に立ちましたか?

解決

このようなもの:

// 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;
}

他のヒント

各入力を個別に読み、個別に処理してみませんか?

すなわち

cout<< " enter 5 digit key 0 to 9 \n";
char str[5];
cin.get(str, 5);

for (int i = 0; i < 5; ++i)
{
    //do something with str[i];
}

次のコードスニペットを使用できます。while ループ。

int i;
cin >> i;

while (i%10 != 0) 
{
  cout << i%10 << endl;
  i = i/10;
}
#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;
}

私はこのようにそれをします

whileループメソッドは、ゼロのない数字のみを処理します。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top