Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

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

with

cin >> nameOfFile

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top