使用 getline 仅读取换行符或文本

Using getline to read either just a newline or text

本文关键字:文本 换行符 读取 getline 使用      更新时间:2023-10-16

所以我需要做的是从用户那里获取输入,特别是文件名,用户只需按 Enter 默认为某个文件名。这是我所拥有的:

cout << "Where should I save the exam (default exam.txt): ";
getline(cin, examfilename);
if (examfilename == "") {
    examfilename = "exam.txt";
}
cout << "Where should I save the key (default key.txt): ";
getline(cin, keyfilename);
if (keyfilename == "") {
    keyfilename = "key.txt";
}

运行时,输出全部Where should I save the exam (default exam.txt): Where should I save the key (default key.txt):在一行上,末尾有一个闪烁的光标。

如果用户按 Enter 键,我如何读取文件名,但也使用默认值?

您可以像这样在控制台中手动引入换行符:

if (examfilename == "") {
    examfilename = "exam.txt";
    cout << endl;
}