-2

ユーザーに数字を尋ねるプログラムを作成する必要があり、ゼロを入力するとゼロを入力したことが出力され、負の数または正の数を入力すると、負または正のいずれかを入力したことが出力されます。正数。文字やコンマなどを受け入れないようにしています。しかし、これを小数を受け入れないようにする方法がわかりませんか? どうすればこれを行うことができますか?cplusplus.com 以外の適切な C++ リファレンスを含む適切なサイト

#include <iostream>
#include <string>
#include <limits>
#include <cmath>
#include <iomanip>
#include <cstdlib>

using namespace std;

    int getInt()
    {
    int choice=0;
    while (!(cin >> choice))
        {
        cin.clear();
        cin.ignore(numeric_limits<streamsize>::max(),'\n');
        cout << "Please input a valid integer: " << '\n';
        }
    return (choice);
    }

int print_zero()
{
 cout << "The number you entered is a zero. " << '\n';
 return 0;
}

int print_negative()
{
 cout << "You entered a negative number. " << '\n';
 return 0;
}

int print_positive()
{
    cout << "You entered a positive number. " << '\n';
    return 0;
}

int main ()
    {

    cout << "your number please:-" << '\n';
    int choice = getInt();

    if (choice == 0)
    {
        print_zero();
    }

    if (choice < 0)
    {
        print_negative();
    }

    if (choice > 0)
    {
        print_positive();
    }

cout << endl << "All done! Nice!!" << endl;

return 0;
}
4

2 に答える 2

0

かなり簡単なことは、次のようなものを使用することです

std::string line;
std::getline(std::cin, line);

size_t pos;
int x = 0;

try
{
  x = std::stoi(line, &pos);

  if (pos < line.length())
  {
    std::cout << "Warning, non-digit character " << line[pos] << " detected!\n"
    return;
  }
}
catch (std::exception&)
{
  std::cout << "That didn't look like an integer to me.\n";
  return;
}

getlineint要求した形式に変換できなかった最初の文字 (たとえば an )で停止するだけでなく、入力からすべてのテキストを取得します。不便な末尾も取り除き\nます。

std::stoistd::stringからへの変換を行いintます。docsを読んでください。注意しないと、例外がスローされる可能性があります。の最初の変換されていない文字の位置を返しますposposが の長さより短い場合line、 に属さない無効な文字がどこかにあることを意味しますint

于 2014-05-20T18:03:15.607 に答える