【问题标题】:Using getline to read either just a newline or text使用 getline 读取换行符或文本
【发布时间】:2013-11-12 12:33:19
【问题描述】:

所以我需要做的是从用户那里获取输入,特别是文件名,或者用户只需按 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): all on a line,最后有一个闪烁的光标。

我怎样才能读入文件名,但如果用户按下回车也使用默认值?

【问题讨论】:

  • 如果examfilename 为空,只打印一个换行符?

标签: c++ newline getline cin


【解决方案1】:

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

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

【讨论】:

  • 这导致它是Where should I save the exam (default exam.txt): 然后是Where should I save the key (default key.txt): 的换行符和第二行末尾的光标。
  • @user1111098 然后需要在另一个if语句的末尾插入一个换行符。
猜你喜欢
  • 2015-01-25
  • 2023-01-21
  • 2015-01-21
  • 1970-01-01
  • 1970-01-01
  • 2023-03-17
  • 2016-07-15
  • 2020-02-27
  • 1970-01-01
相关资源
最近更新 更多