c ++程序在输入时跳过行[控制台应用程序]

问题描述 投票:1回答:2

我正在编写一个关于图书馆管理系统的顺序程序,它由两个结构(书籍和学生)和几个功能组成。

一切都有效,除非我尝试在结构书的函数add_new_book()中获取控制台输入,它在输入时跳过一行。我之前做过研究,然后使用函数cin.ignore()。该函数适用于前两个字符串输入,但在获取前两个输入后,它会跳过剩余的输入行并终止该函数。

下面是结构书和函数add_new_book()的代码

struct books{
    int book_id;
    string book_name;
    string author_name;
    string subject;
    int fine;

};

void add_new_book(){

    struct books b;
    cout << "Enter the Book Name : "; 
    getline(cin, b.book_name);
    cin.ignore();
    //cin >> b.book_name;
    cout << "Enter Author's Name : ";
    getline(cin, b.author_name);
    cin.ignore();
    cout << "Enter Book id : ";
    cin >> b.book_id;

    cout << "Enter Book Cost : ";
    cin >> b.fine;
    cin.ignore();
    cout << "Enter the Subject : ";
    getline(cin, b.subject);

    cout << "\n",b.book_name,b.author_name,b.book_id,b.fine,b.subject;
            cout << "\n\n\t\t SUCCUSSFULLY ADDED \n";
    // open a file in write mode.
    ofstream outfile;
    outfile.open("book1.txt");
    outfile << b.book_name << endl;
    outfile.close();
    admin();
}
c++ function struct console console-application
2个回答
1
投票

我建议摆脱cin.ignore并使用getline作为数字字段,使用std :: string作为临时缓冲区:

string s;
cout << "Enter Book id : ";
//cin >> b.book_id;
getline(cin, s);

在字符串中输入用户输入后,检查其值并最终将其分配给struct字段,例如必须将book id转换为int,这样:

b.book_id = std::atoi(s.c_str());

如果不能执行转换,atoi将返回零

if(b.book_id == 0)
{
   cout << "Invalid book id";
}

此外,cout并不意味着像你一样使用。我会尝试干净整洁的东西,像这样:

cout << "Title : " << b.book_name << endl;
cout << "Author: " << b.author_name << endl;
//etc ...

0
投票

你不应该在std::cin.ignore()之后打电话给std::getline()getline将从该行末尾的输入流中提取'\n'。调用ignore将提取并丢弃另一行。

© www.soinside.com 2019 - 2024. All rights reserved.