- #1
JonnyG
- 233
- 30
I am writing a small practice program to store and retrieve recipes using c++. I ran into a weird problem and I can't seem to figure out the cause of it. Check out this code:
Here is a source file:
Here is my main function:
When I run the program this is the output:
Do you want to store a recipe or retrieve a recipe (s for store, r for retrieve)? s
Enter recipe name: Press any key to continue . . .
Notice that it didn't give me any chance to enter the recipe name? It just reads in a blank space. I was able to fix this by going back to my function getInitialChoice() and changing the cin >> choice to getline(cin, choice), but I don't see why that should make a difference? The difference between cin and getline, as far as I know, is that cin will read up until it encounters a whitespace whereas getline will read up until it encounters a newline. Can someone please explain what's happening there?
Here is a source file:
Recipes.cpp:
string getInitialChoice() {
string choice;
cout << "Do you want to store a recipe or retrieve a recipe (s for store, r for retrieve)? " << endl;
cin >> choice;
return choice;
}
string getRecipeName() {
cout << "Enter recipe name: ";
string recipeName;
getline(cin, recipeName);
return recipeName;
}
main.cpp:
int main() {
string choice = getInitialChoice();
if (choice == "s") {
getRecipeName();
}
}
When I run the program this is the output:
Do you want to store a recipe or retrieve a recipe (s for store, r for retrieve)? s
Enter recipe name: Press any key to continue . . .
Notice that it didn't give me any chance to enter the recipe name? It just reads in a blank space. I was able to fix this by going back to my function getInitialChoice() and changing the cin >> choice to getline(cin, choice), but I don't see why that should make a difference? The difference between cin and getline, as far as I know, is that cin will read up until it encounters a whitespace whereas getline will read up until it encounters a newline. Can someone please explain what's happening there?