从用户输入中获取数字直到用户输入"退出"

时间:2016-02-16 22:49:06

标签: c++ validation input while-loop cin

我正在制作一个程序,允许用户输入任意数量的双打,并将这些双打添加到矢量,直到用户输入"退出"然后它将退出循环。

当用户输入字符串或字符时,我需要此输入函数不会失败,因此while (cin >> x)是不可能的。

所以这是我的代码:

vector<double> input()
{
    double x;
    vector<double> scores;
    cout << "Please enter a score: ";
    while(true)
    {
        x = checkInput();
        scores.push_back(x);
        cout << "Enter another: ";
    }
return scores;
}

double checkInput()
{
    double x;
    cin >> x;
    while(cin.fail())
    {
        cin.clear();
        cin.ignore(numeric_limits<streamsize>::max(), '\n');
        cout << "That is not a number. Please enter another: ";
        cin >> x;
    }
    return x;
}

这样可行,如果用户输入无效输入,则不会中断。但是,正如您所看到的,它永远不会从输入循环中断开。当用户输入==&#34;退出&#34;时,我需要这个来打破并返回分数。我怎样才能做到这一点?

2 个答案:

答案 0 :(得分:0)

使用std::string并转换为int

这是一个片段

double checkInput(bool& dontQuit)
{
    string sx;
    double x;
    while(dontQuit)
    {
        cin >> sx;
        dontQuit = sx != "quit";
        try{
            x = stod(sx);
            break;
        }
        catch(std::exception& e){
            cout << "please Enter a number!: ";
        }
    }
    return x;
}

在这种情况下,您的input()功能会更改......

bool dontQuit = true;
while(dontQuit)
{
    x = checkInput(dontQuit);
    scores.push_back(x);
    cout << "Enter another: ";
}

答案 1 :(得分:0)

我就是这样做的:

operator==

输出: gsamaras @ gsamaras:〜/ Desktop $ g ++ -Wall -std = c ++ 0x px.cpp gsamaras @ gsamaras:〜/ Desktop $ ./a.out

#include <iostream>
#include <vector>
#include <string>
#include <cstdlib>

using namespace std;

bool isOnlyDouble(const char* str) {
    char* endptr = 0;
    strtod(str, &endptr);

    if(*endptr != '\0' || endptr == str)
        return false;
    return true;
}

int main() {
        vector<double> v;
        double d;
        string input;
        while(1) {
                getline(cin, input);
                if(input == "quit")
                        break;
                // else it should be a number
                if(isOnlyDouble(input.c_str())) {
                        d = atof(input.c_str());
                        v.push_back(d);
                } else {
                        cout << "found no number in the string\n";
                }
        }
        for(unsigned int i = 0; i < v.size(); ++i)
                cout << v[i] << endl;
        return 0;
}

这个想法:

  1. 我们正在使用std::getline()循环获取输入。
  2. 如果输入是“退出”,请打破循环。
  3. 否则:
    1. 如果它只包含一个double值,请按下vector。
    2. 否则,请告知用户。
  4. 我决定不从w2.56中提取值,因为它可能是一个错字。

    具有此answer