I have been experimenting with opening previously saved txt files to the console, and also saving console input to a text file at the users desired location. This is working fine but I encountered a getline problem when using it twice within the code. I assume its down to different input types...
int main ()
string text, location, iName, file;
cout << "1. Create a text file. \n2. Open a text file.";
cout << endl << endl << "Selection: ";
cin >> makeOpen;
cout << endl << endl;
if (makeOpen == 1)
cout << " - i.e. This is a save file test!\n";
cout << "Enter text for the save file: ";
cout << endl << " - i.e. C:\\Users\\Admin\\Desktop\n";
cout << "Enter file save location: ";
cin >> location;
cout << endl << " - i.e. saveTest\n";
cout << "Enter file name: ";
cin >> iName;
file = location + "\\" + iName + ".txt";
cout << endl;
cout << "Aces!";
cout << "Boo!";
myfile << text;
else if(makeOpen == 2)
cout << " - i.e. C:\\Users\\Admin\\Desktop\\openTest.txt\n";
cout << "Enter file location and file name: ";
cin >> file;
cout << endl;
ifstream myfile (file);
while ( myfile.good() )
getline (myfile, text);
cout << text << endl;
cout << "Unable to open file.";
cout << "Boo!";
cout << endl << "Enter to exit...";
The error occurs on this line of code:
The error states:
- IntelliSense: no instance of overloaded function "getline" matches the argument list
- IntelliSense: too few arguments in function call
The program compiled and ran- even with errors. If I choose option 1 (create a new text file) it seems to skip the getline and move straight to the next cout and cin without taking input for the input text.
However, I have reopened the project and the errors have gone, but the problem of skipping the getline still occurs.
Thanks for reply- I was assuming the myfile.good() as a condition for the while was okay as I thought it meant the file was opened correctly without error; then the code within the while would be fine to execute. I'll read into the good function a little more.
Lynx thats brilliant. I've never looked into cin.ignore() in great detail- I was only using it to pause the program before exiting (should be using system("pause"); I guess). However I researched and actually came across a similar problem to mine on the forum which was resolved via the ignore function.
I didn't compile or run your code, but I can tell just from looking that it is because you are mixing 'cin' with 'getline'. std::cin leaves the newline character in the buffer after pressing enter, and getline just grabs it and keeps going, that's why getline doesn't block to wait for input.
cin>> will leave newlines in the buffer when the user presses enter. getline() reads this as the user having pressed enter to "skip" the input.
You can use cin.ignore() to get rid of those extra characters before using getline().
Thanks for your help guys. Great, rapid responses to my first post.