Homework Help for Linked List

Hello everyone,

I'm having an odd problem. It's really bugging me that something so small is keeping me from making progress on the rest of my program so I thought that I'd ask for help here!

When I am trying to create a Node to add into my linked list of "Songs", I simply ask the user to enter their information into two temporary string variables.

The problem is...It just skips right over the getline statements and I can't get any input

Here's the "Add song" function where I am having trouble.

any help would be appreciated, thank you!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
void AddSong(Node *& head, Node * nn)
{
	Music a_song;   // temp struct to create a new song node
	string temp_artist;
	string temp_title;

	cout << "Enter Song's artist: ";
	getline(cin, temp_artist);       // skips this statement
	
	cout << "Enter song's title: ";
	getline (cin, temp_title);     // and this one!
	
        a_song.artist = temp_artist;
        a_song.title = temp_title;

	nn = CreateNode(a_song);
	InsertOrdered(head, nn);
}
Last edited on
It may be that a previous input operation has placed std::cin in an error state. Try putting cin.clear(); before asking for input; this clears the error state and allows std::cin to try again.
Thanks L B. adding the cin.clear(); alone didn't fix it, but it did help me remember this piece of code:

1
2
3
4
5
	cout << "Enter song's title: ";
	cin.ignore( cin.rdbuf()->in_avail());
	getline (cin, temp_title);
	cin.clear();
	cin.ignore( cin.rdbuf()->in_avail());


and it works now... weird, but oh well.
Ah, that means you had left-over input that hadn't been processed by previous input statements. I think cin.sync() usually fixes it.
Last edited on
Relying on the behavior of cin.sync() is not portable.
http://www.cplusplus.com/forum/general/63860/
Yep. I don't deal with std::cin much, so I tend to forget. Sorry!
Topic archived. No new replies allowed.