所以我正在阅读有关getline(cin, string);
的内容,并试图用它来提供一个包含多个单词的字符串。
我的简单代码:
#include <iostream>
#include <string>
int main()
{
string test;
getline(cin, test);
cout << test << endl;
return 0;
}
但如果我在一个更复杂的程序中使用相同的代码,它就会被忽略!
我刚刚开始的计划:
#include <iostream>
#include <fstream>
#include <limits>
#include <string>
using namespace std;
struct mainstruct
{
ofstream f_list;
void write()
{
int rating;
string name, watch, wprint;
cout << "Modifying" << endl;
f_list.open ("TextFile.txt", ios::app);
cout << "Name/Title?" << endl;
getline(cin, name);
//cin.clear();
//cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Rating?" << endl;
cin >> rating;
//cin.clear();
//cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Watched or unwatched?" << endl;
getline(cin, watch);
//cin >> watch;
if (watch == "w" || watch == "yes" || watch == "y")
{
watch = "W";
wprint = "Watched";
}
else
{
watch = "DW";
wprint = "Didn't watch";
}
cout << name << " (" << rating << "/10) (" << wprint << ") has been added to the list" << endl;
f_list << name << " " << rating << " " << watch << endl;
//cin.clear();
//cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
void read()
{
cout << "Reading" << endl;
f_list.open("TextFile.txt");
}
void shutdown()
{
f_list.close();
}
};
int main()
{
string answ, test;
mainstruct o_list;
do
{
cout << "\n\nWould you like to check the list, modify or close it?" << endl;
cin >> answ;
if (answ == "modify" || answ == "m" || answ == "write" || answ == "w")
{
o_list.write();
}
else if (answ == "check" || answ == "c" || answ == "read" || answ == "r")
{
o_list.read();
}
else if (answ != "modify" || answ != "m" || answ != "write" || answ != "w" || answ != "check" || answ != "c" || answ != "read" || answ != "r")
{
if (answ == "close" || answ == "quit" || answ == "q")
{
cout << "File closed, list saved" << endl;
}
else
{
cout << "Invalid input" << endl;
}
}
o_list.shutdown();
} while (answ != "close" && answ != "quit" && answ != "q");
o_list.shutdown();
getline(cin, test);
cout << test << endl;
return 0;
}
这里我的getlines被忽略了!
(在此之前我使用了cin >> string;
为什么cin.clear();
和cin.ignore();
&#39}存在。