c++ - 程序跳过一行代码

标签 c++ textinput skip

我已经在这个程序上工作了一段时间,我终于摆脱了编译错误。但是当我尝试的时候,程序基本上跳过了一行代码。

#include <iostream>
#include <cstdlib>
#include <cstring>
using namespace std;
int main(){
  string nameOfFile = "";
  char index;
  char title[100];
  char name[100];
  char copyright[100];

  cout << "Welcome, and hello to the html templating software" << endl;
  cout << "Is this your index page?\ny/n" << endl;

  cin >> index;
  if (index=='n'){
    cout << "Enter the prefered name of this file" << endl;
    getline(cin, nameOfFile, '\n');
  }

  cout << "What will the title of the page be?" << endl;
  cin.getline(title, 100);

  cout << "What is your name?" << endl;
  cin.getline(name, 100);

  cout << "What is the copyright?" << endl;
  cin.getline(copyright, 100);

  cin.get();
  return 0;
}

您会看到在询问这是否是您的索引页面后,它如何跳过下一个 cin.getline 函数,无论情况如何。

最佳答案

当用户输入索引时,他们还输入了换行符,但您的 cin 并未将其从输入流中删除。因此,由于剩余的换行符,您对 cin.getline 的调用会立即返回。

添加对 cin.ignore 的调用在 cin.getline 之前将其清除。

关于c++ - 程序跳过一行代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4241581/

相关文章:

mysql - 仅替换重复项并跳过唯一项

python - 如何通过将某些元素保留在末尾来对Python列表进行排序

c++ - move 分配时左侧 std::vector 资源会发生什么情况?

c++ - std::bind 如何多次调用复制构造函数

jquery - 如何使用Jquery清除html输入文本字段的内容

javascript - 选择 A 单选按钮以在 jquery/javascript 中添加另一个输入

video - GoLang - 通过视频搜索(作为字节)

c++ - 检查有效输入 C++

带有 std::map 的 C++ vector ?

android - react-native TextInput 剪辑文本