program skipping a line of code

陌路散爱 提交于 2019-12-10 16:59:45

问题


I have been working on this program for a while and I finally got rid of the compile errors. But when I tried it, the program basically skipped a line of code.

#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;
}

You see how after asking if this is your index page it skips the next cin.getline function no matter the scenario.


回答1:


When the user entered the index, they also typed a newline, but your cin didn't remove it from the input stream. So, your call to cin.getline returns immediately because of the leftover newline.

Add a call to cin.ignore before the cin.getline to flush it out.




回答2:


replace getline(cin, nameOfFile, '\n')

with

cin >> nameOfFile



来源:https://stackoverflow.com/questions/4241581/program-skipping-a-line-of-code

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!