Issue with user input

All variables are declared properly. For the input for the webpage name, I cannot enter anything with spaces. I've tried putting it into a character array and a string. It's been a while since I've done anything in c++, or any coding at all, and just wanted to get back into it for fun. Can someone help me with this? I just don't know how to enter in the information for that line.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
  				cout << "Author First Name: ";
				cin >> authorFirst;
				cout << "\nAuthor Last Name: ";
				cin >> authorLast;
				cout << "\nName of Webpage: ";
				// SOMEHOW I NEED TO ACCEPT USER INPUT WITH SPACES AND IT WILL NOT WORK, NO MATTER WHAT I TRY - WHAT DO I DO????
				cout << "\nDay Content was Written (number): ";
				cin >> dayWritten;
				cout << "\nMonth Content was Written (name of month): ";
				cin >> monthWritten;
				cout << "\nYear content was written: ";
				cin >> yearWritten;
				cout << "\nMedium (article, document, etc.): ";
				cin >> medium;
				cout << "\nDay Accessed (number): ";
				cin >> dayAccessed;
				cout << "\nMonth Accessed (name of month): ";
				cin >> monthAccessed;
				cout << "\nYear Accessed: ";
				cin >> yearAccessed;
Read the entire line from the user.
1
2
std::string webpage_name; 
std::getline(std::cin, webpage_name); 
^ what mbozzi said.
std::getline can also accept a custom delimiter as a third parameter. By default the getline delimiter is a newline.

Reason why cin couldn't do it: an istream's ">>" operator makes a formatted read, separating tokens on any whitespace (e.g. a space, tab, newline, etc.) by default. The delimiter can be changed, but it takes a bit of work (as per https://stackoverflow.com/questions/7302996/changing-the-delimiter-for-cin-c ).
For some reason, when I try what mbozzi said, it skips over the line. It will output "Name of Webpage" as expected, but then output "Day Content was Written" and accepts input for the day content was written. It just skips right over allowing input for the webpage name.

EDIT: I added cin.ignore(100, '\n'); above the cout statement stating to enter the webpage, and it now works. I take it that the newline character from pressing enter to move to the next prompt was in the stream and was preventing getline from working. I appreciate the help, mbozzi and icy1.
Last edited on
Topic archived. No new replies allowed.