2017-04-04 68 views
0

在嘗試使Do/While循環正常工作時,遇到一些困難,找出了正確的語法。我想用C++編寫一個計算器,它允許用戶輸入一個字符串,然後執行它的操作並輸出結果,詢問用戶是否要再次出現。儘管循環跳過C++中的用戶輸入

我有一個簡單的主要功能,目前爲止只是爲了獲得Do/While循環,但是當我輸入y或Y時,程序只是詢問我是否想再次繼續,它不會給我機會運行「計算器」部分。我究竟做錯了什麼?

#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

+0

無法重現。你的循環似乎工作。然而,代碼在某些輸入中斷(例如,包含「ä」)。 – wkl

+1

這可能取決於您如何輸入輸入。 'cin >> userInput;'只讀取一個單詞並停在第一個空白處,剩下的放在輸入緩衝區中。 –

+0

@wkl我會得到一張圖片並將其添加到我的帖子中,以便您可以看到我所得到的。 –

回答

4

的問題是,cin >> userInput;停在第一空白,我的錢是含有很多,其中你的一個典型的輸入字符串。

更改爲

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

這將吞噬輸入的整條生產線,並與換行符自動爲您處理。

爲了讓生活更輕鬆,請使用類似於ans的東西。將其重新定義爲std::stringstd::string甚至有==重載爲char類型!

(我個人倒也評論標準#include文件避免。任何C++程序員應該知道什麼,他們「引進來」,併爲你的程序擴展,這可能導致假。)

+0

所以即使使用'getline',執行也是一樣的,它只是跳過輸入另一個字符串的機會 –

+0

你是否改變了ans的類型?如果我是你,我會這麼做。 – Bathsheba

+0

我也不明白爲什麼我需要改變'ans'的類型我已經將它定義爲'char',因爲用戶只會輸入一個字符? @Bathsheba –

0

所以我終於克服我的問題來自@Bathsheba和@mutantkeyboard幫助

我使用的是getline,但僅用於用戶輸入的第一個實例,就像@Bathsheba所示。這對我不起作用,因爲我然後將ans的輸入保留爲cin。把它們都改成getline不只是其中之一,並且使用沒有預編譯頭的空白項目已經解決了我的問題。項目現在按預期正確循環。

謝謝大家的幫助!