Program skipping a line of code

I worked on this program for a while, and I finally got rid of compilation errors. But when I tried, 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 regardless of the script.

+4
source share
2 answers

When the user entered the index, they also typed a new line, but your cin did not remove it from the input stream. So, your call to cin.getline is immediately returned due to the remaining line of the new line.

Add a call to cin.ignore before cin.getline exits.

+5
source

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

with

cin → nameOfFile

0
source

All Articles