Do While循环在C ++中跳过用户输入

时间:2017-04-04 09:33:04

标签: c++ while-loop do-while

在尝试使Do / While循环工作时,我应该使用正确的语法。我想用C ++编写一个计算器,允许用户输入一个字符串然后它完成它并打印结果,询问用户是否要再次使用。

到目前为止,我有一个简单的主要功能只是为了让Do / While循环正确,但是当我输入y或Y时,程序只是询问我是否想再次继续,它不会让我有机会运行& #34;计算器"再一次。我做错了什么?

#include "stdafx.h"
#include <iostream> //cout, cin
#include <string> //string
#include <algorithm> //remove_if(), end(), begin(), erase()
#include <stack> //stack<type>
#include <ctype.h> //isdigit()
#include <vector> //vectors
#include <stdlib.h>

using namespace std;

int main()
{
    string userInput = ""; //declaring and initialising a string called user input
    char ans;

    do {

        cout << "Welcome to the calculator, please enter your calculation and then press enter when you are done." << endl;
        cin >> userInput;

        userInput.erase(remove_if(userInput.begin(), userInput.end(), isspace), userInput.end()); //removes and then erases any spaces in the string
        userInput.erase(remove_if(userInput.begin(), userInput.end(), isalpha), userInput.end()); // removes and then erases any alphabetic charecters
                                                                                                  //this will leave only numbers and operators
        cout << userInput << endl;
        cout << "Would you like to continue?" << endl;
        cout << "Please enter 'y' or 'n'" << endl;
        cin >> ans;

    } while ((ans == 'y')||(ans == 'Y'));

    return 0;
}

This is what I get in the Termninal

2 个答案:

答案 0 :(得分:4)

问题是cin >> userInput;在第一个空格处停止,而我的钱是在你的大量输入字符串中包含的。

更改为

std::getline(std::cin, userInput);

这将吞噬整行输入,并自动处理换行符。

为了过上轻松的生活,请使用ans做类似的事情。将其重新定义为std::string。对于std::string类型,==甚至已经重载了char

(我个人也不会评论标准#include文件。任何C ++程序员都应该知道他们带来了什么&#34;,这可能会导致程序扩展时出现错误信息。 )

答案 1 :(得分:0)

所以我终于在@Bathsheba和@mutantkeyboard的帮助下克服了我的问题

我正在使用getline但仅用于第一个用户输入实例,如@Bathsheba建议的那样。这对我不起作用,因为我将ans的输入留作cin。将这两个更改为getline而不仅仅是其中一个并使用没有预编译头的空白项目已经解决了我的问题。现在项目按预期正确循环。

感谢大家的帮助!