getline() 函数的问题

Problems with getline() function?

本文关键字:问题 函数 getline      更新时间:2023-10-16

我对下面代码中的getline函数有问题。在"获取"信息部分,我希望能够存储整个句子,但我无法使其工作。

当我打开我的程序时,它只是跳过信息的输入。

p.s:我是C++新手

这是我遇到问题的代码部分(输入信息):

void add() {
    string name;
    string faction;
    string classe;
    string race;
    string info;
    ofstream wowdatabase("wowdatabase.txt", ios::app);
    cout << "Add a race or class" << endl;
    cout << "---------------------------------------------------------" << endl;
    cout << "" << endl;
    cout << "Enter the name of the race or class (only small letters!):" << endl;
    cin >> name;
    cout << "Enter Race (Type -, if writen in name section):" << endl;
    cin >> race;
    cout << "Enter Class (Type -, if writen in name section):" << endl;
    cin >> classe;
    cout << "Enter faction (Alliance/Horde):" << endl;
    cin >> faction;
    cout << "Enter the information:" << endl;
    getline(cin, info);
    wowdatabase << name << ' ' << faction << ' ' << classe << ' ' << race << ' ' << info << endl;
    wowdatabase.close();
    system("CLS");
    main();
}

现在它工作正常=)但是,当我想再次输出信息时,它只显示句子中的第一个单词?

在此语句之前

getline(cin, info);

进行以下调用

cin.ignore( numeric_limits<streamsize>::max(), 'n' );

要使用此调用,必须包含标头<limits>

问题是执行语句后

cin >> faction;

对应于 enetered 键 ENTER 的换行符位于输入缓冲区中,下一个 getline 调用将读取此字符。

读取分数后,将留下一个空行字符。随之而来的对getline的呼吁将阅读它。为了避免这种情况,请在getline调用之前向 cin.ignore 添加调用。