cin.getline的奇怪错误

时间:2011-04-09 16:00:27

标签: file text

任务要求是请求文本文件中的输出行数,然后逐行请求输入。每行包含2个数字并排。示例文件将是:

4 75 65 80 75 90 85 55 65

我尝试编写代码,但是,似乎缺少一行输入。你能帮帮我吗?非常感谢!!

int main() {

char file_name[81];
char buffer[81];
int lines;

cout << "input file name: ";
cin.getline(file_name,81);

cout << "input number of lines: ";
cin >> lines;

ofstream out_file(file_name);
if (!out_file)
{
    cout << "\nerror, file already exists. choose another file name.";
    return 0;
}

while (lines != 0)
{
    cout << "enter first number: "; cin.getline(buffer, 81);
    out_file << buffer << "\t";

    cout << "\nenter second number: "; cin.getline(buffer ,81);
    out_file << buffer << endl;

    lines--;

}


out_file.close();

cout << "\nprogram terminated";

cout << endl; return 0;

}

1 个答案:

答案 0 :(得分:0)

cout << "input number of lines: ";
cin >> lines;

添加

cin.ignore(1);