ちょっと、人から新しいタスクを受け取り、スタックに追加し、タスクを表示し、そのスタックをテキストファイルに保存できるようにするプログラムを作成しようとしていますテキストファイルを読んでください。この問題は、スペースを含む文字列を入力するたびにユーザーからの入力を受け入れるときに、ループだけを実行するメニューを選択するときに発生します。私はこれを解決する方法が必要です。どんな助けでも大歓迎です。C++でgetlineを使用してスペースを無視する
//get the input from the user
cin >> option;
cin.ignore();
そしてcin.ignore()
は必要ありません、あなたの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オプション'の前に 'cin.ignore()'を使うことができます。 –
すべての入力操作についてエラーチェックを実行する必要があります(たとえば、 'if(!std :: cin){/ * handle error * /}'のようなストリームをテストし、入力ループが正しくない場合)入力ループ、[別の質問へのこの回答](http://stackoverflow.com/questions/4258887/semantics-of-flags-on-basic-ios/4259111#4259111)を参照してください。 –
エステートのために:スイッチ/ケース/ default'をブロックは、これらすべての '場合/他の場合/ else' ... – Emmanuel