c++ - C++ 中两个 gets() 的用法

标签 c++ getchar gets

我正在学习 C++ 类。我使用类的概念编写了一个简单的程序。在程序中,我需要人输入书籍的详细信息。这是该函数:

void Book::add(){
cout << "Enter name of Book: ";
gets(book_name);gets(book_name);
cout << "\n\nPlease enter the book id: ";
cin >> book_id;
cout << "\n\nThank you the book has been added.";
total++;
input = getchar();
getchar();
}

请注意,在第三行中,我必须使用两次获取来获取用户输入。如果我用一个 get this is the output. It just skips the gets statement.同样,在其他地方我也必须使用两个 getchar 语句。我能够在 SO 本身上找到答案。例如 Why my prof. is using two getchar 。不过,我找不到两个 gets 语句的答案。 Here is the complete code如果需要的话。

最佳答案

这是因为流中剩余一个尾随换行(来自Enter)字符,该字符未被第一个读取操作读取。因此,第一个 gets(book_name) 将读取该内容并继续处理下一个输入请求。

使用 getline 从流中删除任何剩余的违规输入。

void Book::add(){
    string garbage;
    getline(cin,garbage);  // this will read any remaining input in stream. That is from when you entered 'a' and pressed enter.
    cout << "Enter name of Book: ";
    gets(book_name);
    getline(cin,garbage);  // this will read any remaining input in stream.
    cout << "\n\nPlease enter the book id: ";
    cin >> book_id;

无论如何,只需使用更安全的方式从流中读取输入

cin >> book_name;

而不是获取。那么你就不会有这样的问题了。


如果要将空格分隔的输入读取到一个字符串中,请使用 std::getline (就像我对上面的垃圾所做的那样)

std::getline(cin,book_name);

关于c++ - C++ 中两个 gets() 的用法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16383823/

相关文章:

c - scanf 无法检测到 EOF 但 getchar 能够检测到 EOF 输入?

由于 getchar 导致崩溃

c - Gets(string#) 函数跳过先获取请求

c - 退出 Do While 循环

c++ - 是否根据最新的 C++ 标准保留以下划线开头的标识符?

c++ - gmtime 给我一些本地时间?

c - 使用 getchar() 是/否用户提示

c++ - 如何在 nodejs 插件中泵送窗口消息?

c++ - 未定义的函数引用 (c++)

c - 使用 gets() 将字符串保存到结构中?