嘿,我試圖編寫一個程序,它將接受來自人員的新任務,將它添加到堆棧,能夠顯示任務,能夠將該堆棧保存到文本文件,然後閱讀文本文件。當我試圖接受來自用戶的輸入時,只要輸入一個帶有空格的字符串,菜單選擇剛剛循環的內容,就會出現問題。我需要一種方法來解決這個問題。任何幫助將不勝感激。忽略空格在C++中使用getline
// basic file io operations
#include <iostream>
#include <fstream>
#include <stack>
#include <string>
using namespace std;
int main() {
//Declare the stack
stack<string> list;
//Begin the loop for the menu
string inputLine;
cout << "Welcome to the to-do list!" << endl;
//Trying to read the file
ifstream myfile ("to-do.txt");
if(myfile.is_open()){
//read every line of the to-do list and add it to the stack
while(myfile.good()){
getline(myfile,inputLine);
list.push(inputLine);
}
myfile.close();
cout << "File read successfully!" << endl;
} else {
cout << "There was no file to load... creating a blank stack." << endl;
}
int option;
//while we dont want to quit
while(true){
//display the options for the program
cout << endl << "What would you like to do?" << endl;
cout << "1. View the current tasks on the stack." << endl;
cout << "2. Remove the top task in the stack." << endl;
cout << "3. Add a new task to the stack." << endl;
cout << "4. Save the current task to a file." << endl;
cout << "5. Exit." << endl << endl;
//get the input from the user
cin >> option;
//use the option to do the necessary task
if(option < 6 && option > 0){
if(option == 1){
//create a buffer list to display all
stack<string> buff = list;
cout << endl;
//print out the stack
while(!buff.empty()){
cout << buff.top() << endl;
buff.pop();
}
}else if (option == 2){
list.pop();
}else if (option == 3){
//make a string to hold the input
string task;
cout << endl << "Enter the task that you would like to add:" << endl;
getline(cin, task); // THIS IS WHERE THE ISSUE COMES IN
cin.ignore();
//add the string
list.push(task);
cout << endl;
}else if (option == 4){
//write the stack to the file
stack<string> buff = list;
ofstream myfile ("to-do.txt");
if (myfile.is_open()){
while(!buff.empty()){
myfile << buff.top();
buff.pop();
if(!buff.empty()){
myfile << endl;
}
}
}
myfile.close();
}else{
cout << "Thank you! And Goodbye!" << endl;
break;
}
} else {
cout << "Enter a proper number!" << endl;
}
}
}
你可以嘗試在`cin >> option`之前使用'cin.ignore()`。 – 2011-02-02 16:27:23
您需要對所有輸入操作執行錯誤檢查(通過測試流,例如`if(!std :: cin){/ * handle error * /}`,並且您的輸入循環不正確:如何編寫正確的輸入循環,請參閱[這個答案的另一個問題](http://stackoverflow.com/questions/4258887/semantics-of-flags-on-basic-ios/4259111#4259111)。 – 2011-02-02 16:27:40