【问题标题】:How to allow only numbers in a variable?如何只允许变量中的数字?
【发布时间】:2017-07-20 02:21:45
【问题描述】:

我的代码有一些问题,这是我遇到问题的代码的一部分。

这段代码的要点是,如果用户输入的不是数字,例如字符p,程序应该要求用户再次输入,这部分有效。

如果用户输入了数字和字符的组合,程序应该要求用户再次输入。例如 n1212n 无效。

字符首先出现的部分,如n12 不会导致问题,但问题出现在数字在前,其他内容在后的情况下,如12n,这是无效的,但我的代码打印出号码12 后说该号码无效。

#include <iostream>

using namespace std;

int main ()
{
    int n;

    while(1)
    {

        cout<<"Enter a number, 0 for exit: ";
        cin>>n;

        if(!cin)
        {
            cout<<"You didnt enter a valid number\n";
            cin.clear();
            cin.ignore(1000,'\n');
            continue;
        }
        cout<<"Number is: "<<n<<endl;

        if(n==0) return 0;
    }
}

代码输出示例:

Enter a number, 0 for exit: 12
Number is: 12

Enter a number, 0 for exit: n
You didnt enter valid number

Enter a number, 0 for exit: n12
You didnt enter valid number

Enter a number, 0 for exit: 12n
Number is: 12
Enter a number, 0 for exit: You didnt enter valid number

编辑:如果可能的话,我想在不包括其他库的情况下解决这个问题。

【问题讨论】:

  • cin &gt;&gt; n; 之后你可以做一个getline 然后检查它是否是一个空字符串
  • 这不是“问题”,而是cin..的明确行为。
  • @nbro:如果您不知道如何实现预期目标,这可能仍然是个问题。
  • @derM 确实,这就是为什么我编辑我的评论以用引号括住单词问题。
  • @noobcoder 你有没有考虑过接受一个答案,如果你的问题当然解决了,那么问题就被标记为已解决?

标签: c++ io numbers iostream cin


【解决方案1】:

您可以使用来自其他标准库的isdigit()std::stringstd::all_of()(这没关系,不是矫枉过正),就像这样(将输入存储在字符串中,然后检查是否存在isdigit 函数成功的那个字符串,这意味着在这种情况下输入纯数字):

#include <iostream>
#include <cctype>
#include <string>

int main()
{
    std::string str;
    std::cin >> str;
    (std::all_of(str.begin(), str.end(), [] (char c) { return isdigit(c); })) ? std::cout << "It's a number!\n" : std::cout << "isdigit() failed\n";
    return 0;
}

输出:

Georgioss-MacBook-Pro:~ gsamaras$ g++ -Wall -std=c++0x main.cpp 
Georgioss-MacBook-Pro:~ gsamaras$ ./a.out 
4
It's a number!
Georgioss-MacBook-Pro:~ gsamaras$ ./a.out 
f
isdigit() failed
Georgioss-MacBook-Pro:~ gsamaras$ ./a.out 
12n
isdigit() failed

【讨论】:

    【解决方案2】:

    您需要检查用户输入的整行,而不仅仅是其中的一部分。 istream::operator&gt;&gt; 在遇到不属于当前正在读取的数据类型的字符时停止读取。这就是为什么像12n 这样的输入会被分别处理为12n

    您不会仅使用&lt;iostream&gt; 功能来解决此问题。最好使用std::getline()std::stoi()/std::strtol() 之类的东西来处理,例如:

    #include <iostream>
    #include <string>
    
    using namespace std;
    
    bool to_int(const string &str, int &i)
    {
        size_t pos;
        i = stoi(str, &pos);
        return (str.c_str()[pos] == '\0');
    }
    
    int main ()
    {
        string line;
        int n;
    
        do
        {
            cout << "Enter a number, 0 for exit: ";
            getline(cin, line);
    
            if (!to_int(line, n))
            {
                cout << "You didn't enter a valid number\n";
                continue;
            }
    
            cout << "Number is: " << n << endl;
    
            if (n == 0) break;
        }
        while (1);
    
        return 0;
    }
    

    如果您不想使用std::stoi() 之类的转换函数,至少可以改用std::istringstream

    #include <iostream>
    #include <string>
    #include <sstream>
    
    using namespace std;
    
    bool to_int(const string &str, int &i)
    {
        char c;
        istringstream iss(str);
        iss >> i;
        return !(iss.fail() || iss.get(c));
    }
    
    int main ()
    {
        string line;
        int n;
    
        do
        {
            cout << "Enter a number, 0 for exit: ";
            getline(cin, line);
    
            if (!to_int(line, n))
            {
                cout << "You didn't enter a valid number\n";
                continue;
            }
    
            cout << "Number is: " << n << endl;
    
            if (n == 0) break;
        }
        while (1);
    
        return 0;
    }
    

    【讨论】:

      【解决方案3】:

      循环遍历数字,如果它不是数字,则打印“您没有输入有效数字”,否则打印数字。我们将以字符串的形式获取输入,并使用 ctype.h 来验证字符串的字符是否为数字:

      #include <iostream>
      #include <string>
      #include <ctype.h>
      using namespace std;
      
      int main()
      {
          string n;
          bool is_valid = true;
      
          while (1)
          {
      
              cout << "Enter a number, 0 for exit: ";
              cin >> n;
              for (size_t i = 0; i < n.length(); i++) {
      
                  if (!isdigit(n[i])) {
                      cout << "You didnt enter a valid number\n";
                      is_valid = false;
                      break;
                  }
              }
              if (is_valid) cout << "Number is: " << n << endl;
      
              if (n == "0") return 0;
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-10-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-02-07
        相关资源
        最近更新 更多