在嘗試使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;
}
無法重現。你的循環似乎工作。然而,代碼在某些輸入中斷(例如,包含「ä」)。 – wkl
這可能取決於您如何輸入輸入。 'cin >> userInput;'只讀取一個單詞並停在第一個空白處,剩下的放在輸入緩衝區中。 –
@wkl我會得到一張圖片並將其添加到我的帖子中,以便您可以看到我所得到的。 –