标题是不言自明的。由于某种原因,在 int main() 的循环中,如果用户想输入另一本书,循环会跳过第一个函数的输入,直接询问作者姓名。例如:
标题:指环王
作者:J.R.R.托尔金
版权:1954
输入以空格分隔的 ISBN 编号:1 2 3 x
checkout ?(是或否):是
Are you finished?(Y or N): N//这开始循环,Y 将发出中断
Title://这一行和下一行之间实际上没有空格,应该有空格
作者://它跳到这一行,不允许用户输入标题,如果用户继续输入信息,这个循环将继续 - 总是跳过标题的输入
代码:
#include "std_lib_facilities.h"
class Book{
public:
vector<Book> books; // stores book information
Book() {}; // constructor
string what_title();
string what_author();
int what_copyright();
void store_ISBN();
void is_checkout();
private:
char check;
int ISBNfirst, ISBNsecond, ISBNthird;
char ISBNlast;
string title;
string author;
int copyright;
};
string Book::what_title()
{
cout << "Title: ";
getline(cin,title);
cout << endl;
return title;
}
string Book::what_author()
{
cout << "Author: ";
getline(cin,author);
cout << endl;
return author;
}
int Book::what_copyright()
{
cout << "Copyright Year: ";
cin >> copyright;
cout << endl;
return copyright;
}
void Book::store_ISBN()
{
bool test = false;
cout << "Enter ISBN number separated by spaces: ";
while(!test){
cin >> ISBNfirst >> ISBNsecond >> ISBNthird >> ISBNlast;
if((ISBNfirst<0 || ISBNfirst>9) || (ISBNsecond<0 || ISBNsecond>9) || (ISBNthird<0 || ISBNthird>9))
error("Invalid entry.");
else if(!isdigit(ISBNlast) && !isalpha(ISBNlast))
error("Invalid entry.");
else test = true;}
cout << endl;
}
void Book::is_checkout()
{
bool test = false;
cout << "Checked out?(Y or N): ";
while(!test){
cin >> check;
if(check == 'Y') test = true;
else if(check == 'N') test = true;
else error("Invalid value.");}
cout << endl;
}
int main()
{
Book store;
char question = '0';
while(true){
store.what_title();
store.what_author();
store.what_copyright();
store.store_ISBN();
store.is_checkout();
store.books.push_back(store);
cout << "Are you finished?(Y or N): ";
cin >> question;
if(question == 'Y') break;
else if(question == 'N') cout << endl;
else error("Invalid value.");
}
cout << endl;
keep_window_open();
}
如果您对 keep_window_open() 和 error() 等函数感兴趣,可以在此处找到 header 信息,但它与此问题无关。 - http://www.stroustrup.com/Programming/std_lib_facilities.h
如有任何帮助,我们将不胜感激 - 谢谢。
最佳答案
下面一行:
cin >> question;
读入“Y”或“N”字符。输入输入时,您还可以键入“返回”或“输入”。该返回/输入仍在缓冲区中。当你到达 getline(cin,title); 第二次通过循环时,仍然在缓冲区中的 return/enter 被读入并解释为整行。
您需要做的是使用 cin.flush() 清除输入缓冲区;或者您需要将问题作为字符串而不是字符来阅读。
你的代码应该是这样的
int main()
{
Book store;
char question = '0';
while(true){
store.what_title();
store.what_author();
store.what_copyright();
store.store_ISBN();
store.is_checkout();
store.books.push_back(store);
cout << "Are you finished?(Y or N): ";
cin >> question;
if(question == 'Y') break;
else if(question == 'N')
{
cout << endl;
cin.flush();
}
else error("Invalid value.");
}
cout << endl;
keep_window_open();
}
关于c++ - 循环后跳过第一个函数输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1144399/