문제

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.

도움이 되었습니까?

해결책

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.

다른 팁

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

with

cin >> nameOfFile

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top