程序返回多个结果

时间:2013-05-19 22:08:39

标签: c++

我正在编写一个基本的随机数猜测游戏,我想在输入非法字符时尝试完善它,只要输入1-100范围之外的数字,程序就会告诉用户和用户可以重做它,与字母相同。但是,如果您输入23x5,最终会收到双重错误消息,根据随机数,您会同时收到字母和太高/太低。如何对其进行排序,以便此条目也会出现在字母错误消息下?

这是我的代码: 的 Header.h

#ifndef HEADER_H
#define HEADER_H

int nGuessedNumber;
int nNumberOfGuesses = 1;
int nRandomNumber;

int UserInput();


#endif

Source.cpp

#include "stdafx.h"
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

extern int nGuessedNumber;

int UserInput()
{
    while(!(cin >> nGuessedNumber))
        {
            cin.clear();
            while(cin.get() != '\n'){}

            cout << "I asked for a number between 1 and 100.\n";
        }
    return nGuessedNumber;
}

的main.cpp

#include "stdafx.h"
#include <iostream>
#include <cstdlib>
#include <ctime>
#include "Header.h"
using namespace std;

int main()
{
    srand(time(0));
    nRandomNumber = rand() % 100 + 1;// sets random number between 1 and 100

    cout << "Guess a number from 1 too 100: " << endl;
    UserInput();

    while (nGuessedNumber != nRandomNumber)
    {
        if ((nGuessedNumber < 1) || (nGuessedNumber > 100))
        {
            cout << "Oi! Between 1 and 100!\n";
            UserInput();
        }
        else
        {
            if (nGuessedNumber < nRandomNumber)
            {
                for (nGuessedNumber; nGuessedNumber < nRandomNumber; nNumberOfGuesses++)
                {
                    cout << "Too low, try again!" <<endl;
                    UserInput();
                }
            }
            else if (nGuessedNumber > nRandomNumber)
            {
                for (nGuessedNumber; nGuessedNumber > nRandomNumber; nNumberOfGuesses++)
                {
                    cout << "Too high, try again!"<< endl;
                    UserInput();
                }
            }
        }
    }
    if (nGuessedNumber == nRandomNumber)
    {
        cout << "Congratulations! " << nGuessedNumber << " is correct!" << endl;
        cout << "You guessed " << nNumberOfGuesses << " times." << endl;
    }
    system("PAUSE");
    return 0;
}

1 个答案:

答案 0 :(得分:2)

std::cin读取整行,并使用std::istringstream

分别解析它们
int UserInput()
{
    std::string line;
    while (getline(std::cin, line)) {
        std::istringstream is(line);
        if (is >> nGuessedNumber) {
            ...
            return nGuessedNumber;
        } else {
            ...
        }
    }
}