仅使用if else语句接受C ++程序中的数字

时间:2014-08-16 14:27:50

标签: c++

我做了一个简单的程序,用户可以投票。在这里,我已经截断了实际代码,因此其他用户不必浪费时间。正如您所看到的,while循环不起作用,但该程序使用if else语句。我也在评论自己对程序的理解 所以你可以指出我在这里做错了什么。请注意,我已尝试过所有循环,但我不知道它为什么不起作用。对不起是菜鸟,是的,我感谢您努力回答我的问题,昨天该网站进入了只读模式,所以我无法在此更新或评论。无论如何,这是我的代码

这是我的计划,我遇到问题:

    #include <iostream>
    #include <string>
    #include <sstream>

    int main (void)

    {
        int pollVote = 0;
        std::string pollVoteString;

        do
        {
            std::cout << "Enter your vote: \n";
            getline (std::cin, pollVoteString, '\n');
            std::stringstream verifyPoll(pollVoteString);

        while (!(verifyPoll >> pollVote && verifyPoll.eof())) // To accept only numbers :)
        {
            std::cout << "Invalid number entered! Try again.\n";
            getline (std::cin, pollVoteString, '\n');

        }

        } while (!(pollVote > 0 && pollVote < 4));

        std::cout << "Thanks for voting!\n";
    }

以下是使用if else的工作程序:

#include <iostream>
#include <string>
#include <sstream>

int main (void)

{
    int pollVote = 0;                     //setting to 0 to make the do while loop work
    std::string pollVoteString;           // creating a new string

    do
    {
        std::cout << "Enter your vote: \n";           //asking user to enter a vote
        getline (std::cin, pollVoteString, '\n');    // saving the input as string
                                                     // in "pollVoteString" variable

            while (true)                   // starting infinite loop
        {
            //the stringstream will create a new variable called verifyPoll
            //and read data from "pollVoteString" and save it in "verifyPoll"

            std::stringstream verifyPoll(pollVoteString);


            // if "verifyPoll" can insert data to "pollVote" 
            // and "verifyPoll" don't have more than one data type then it will break.

            if (verifyPoll >> pollVote && verifyPoll.eof()) 
            {
                break; // Success :D
            }
           //otherwise ask the user to enter the vote again.
           else
            {
                std::cout << "Invalid number! Try again.\n";
                getline (std::cin, pollVoteString, '\n');
            }
        }

    } while (!(pollVote > 0 && pollVote < 4));    //Making sure that the vote is 1,2 or 3.

    std::cout << "Thanks for voting!\n";          //checking the exit from the loop.
}

1 个答案:

答案 0 :(得分:1)

你已经颠倒了考试的感觉。您的for循环可以写为while循环:

while (verifyPoll >> pollVote && verifyPoll.eof()) {
    // ...
}

你想要的是

while (!(verifyPoll >> pollVote && verifyPoll.eof())) {
}

此外,您不得在循环体中声明新的verifyPoll,因为现在如果第一个答案未验证,则循环不会终止。您可以改为使用

分配新字符串
verifyPoll.str(pollVoteString);

但您应该在getline之后执行此操作。