程序跳过一行代码

时间:2010-11-22 01:46:29

标签: 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函数。

2 个答案:

答案 0 :(得分:5)

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

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

答案 1 :(得分:0)

替换getline(cin,nameOfFile,'\ n')

cin&gt;&gt; nameOfFile

相关问题