0

I am trying to create a database where the user can input certain data to be stored in a csv file. This is a console based application as im a beginner. I have a switch statement which is used to direct the user to a function based on their choice. The switch statement works well but when the addingdata() function gets called:

{
    ofstream newData;
    newData.open("TreeDatabase.csv", ios::app); 
    
    cout << "Enter tree species: " << endl; 
    getline(cin, treeSpecies);

    cout << "Enter tree name: " << endl;
    getline(cin, treeName);

    return 0;
}

All the cout statements seem to get called at once without waiting for the user input whereas in the main() function, the user input is taken in first before moving onto the next cout statement. Why is this?

David C. Rankin
  • 81,885
  • 6
  • 58
  • 85
  • 1
    I don't see any switch statement, but that is not relevant. What is generally behind symptoms like this, is that there is stuff remaining in the input buffer that immediately fills later requests for input. This usually happens when someone tries to mix usage os `cin >>` and `getline`. I'd guess that in your real code you had a `cin >>` earlier in your code. – Avi Berger Aug 21 '22 at 04:12

1 Answers1

-2

I believe this is happening because you are adding making a new line after the cout

According to the CPP Docs, it waits for the new line character, so the program already has the new line character and just continues onwards

I am not a master at CPP so I may be wrong, check out the documentation below.

getline Documentation

This is what I would change the code to:

ofstream newData;
newData.open("TreeDatabase.csv", ios::app); 


cout << "Enter tree species: "; // removed >> endl 
getline(cin, treeSpecies);

cout << "Enter tree name: "; // removed >> endl 
getline(cin, treeName);



return 0;

Cheers, Daniel

  • 2
    That's not how it works. A program's standard input and standard output streams are separate and unrelated. Data written to standard output will not appear in standard input (unless you've done some really nasty I/O redirection shenanigans). – Miles Budnek Aug 21 '22 at 04:24