【问题标题】:C++ - Sanitize Integer Whole Number InputC++ - 清理整数整数输入
【发布时间】:2014-04-21 23:19:21
【问题描述】:

我目前正在使用我在另一个 StackOverflow 帖子中找到的函数(我找不到它),我以前使用过,名为“GetInt”。我的问题是,如果用户输入诸如“2 2 2”之类的内容,它会将其放入我接下来的两个 Cin 中。我试过 getLine,但它需要一个字符串,我正在寻找一个 int 值。我将如何构造检查以清理大于 2 的整数值并向2 2 2 答案抛出错误。

#include <iostream>
#include <string>
#include <sstream>
#include "Board.cpp"
#include "Player.cpp"

using namespace std;

int getInt()
{
int x = 0;
while (!( cin >> x))
{
    cin.clear();
    cin.ignore(numeric_limits<streamsize>::max(), '\n');

    cout << "Please input a proper 'whole' number: " << endl;
}
return (x);
}

和我的电话

do
{
    //do
    //{
        cout << "How many players are there? \n";
        numberOfPlayers = getInt();
    //} while (isdigit(numberOfPlayers) == false);
} while (numberOfPlayers < 2);

编辑:

我选择了贾斯汀的答案,因为它最接近我的原始代码,并且在没有进行重大更改的情况下解决了问题。

【问题讨论】:

    标签: c++ input int


    【解决方案1】:

    将您的代码更改为:

    int getInt()
    {
        int x = 0;
        while (!( cin >> x))
        {
            cin.clear();
            cin.ignore(numeric_limits<streamsize>::max(), '\n');
    
            cout << "Please input a proper 'whole' number: " << endl;
         }
    
         cin.clear();
         cin.ignore(numeric_limits<streamsize>::max(), '\n');
         return (x);
     }
    

    只有在整数收集失败时才会调用您在收到整数后忽略该行其余部分的代码(例如,您键入“h”作为玩家人数)。

    【讨论】:

      【解决方案2】:

      您与std::getline 走在了正确的轨道上。您将整行读取为字符串,然后将其放入std::istringstream 并读取整数。

      std::string line;
      if( std::getline(cin, line) ) {
          std::istringstream iss(line);
          int x;
          if( iss >> x ) return x;
      }
      // Error
      

      这将具有丢弃整数之后的任何绒毛的效果。只有在没有输入或无法读取整数时才会出错。

      如果您希望在整数之后出现内容时出现错误,您可以利用从流中读取字符串的方式。任何空格都可以,但其他任何内容都是错误:

          std::istringstream iss(line);
          int x;
          if( iss >> x ) {
              std::string fluff;
              if( iss >> fluff ) {
                  // Error
              } else {
                  return x;
              }
          }
      

      【讨论】:

        【解决方案3】:

        整数由空格分隔,输入 2 2 2 只是多个整数。如果您想确保每行只输入一个整数,您可以跳过空白字符,直到找到换行符。如果在换行符之前发现非空格,您可能会发出错误:

        numberOfPlayers = getInt();
        int c;
        while (std::isspace(c = std::cin.peek()) && c != '\n') {
            std::cin.ignore();
        }
        if (c != std::char_traits<char>::eof() && c != '\n') {
            // deal with additional input on the same line here
        }
        

        【讨论】:

          猜你喜欢
          • 2014-07-19
          • 2012-11-02
          • 1970-01-01
          • 2013-02-20
          • 2020-11-14
          • 2011-12-02
          • 2019-06-02
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多