hi, i have this code:

#include <iostream>
#include <fstream>
#include<cstdio>
#include<cstdlib>
using namespace std;

int main (char argc) 
{
    for(;;)
    {
           fstream myfile;
           myfile.open("example.txt");
           cout << "1: Write" << endl;
           cout << "2: Read" << endl;
           int n1;
           cin >> n1;
           
           if(n1 == 1)
           {
                 string n2;
                 getline(cin,n2);
                 myfile << n2 << endl;
           }
           
           if(n1 == 2)
           {
                 string n3;
                 getline(myfile,n3);
                 cout << n3 << endl;
           }
           myfile.close();
}
}

when i run it, i want to write to the file but when i press 1, the program just goes back to the main menu. any solutions?

Edited 5 Years Ago by thecoolman5: n/a

The way you wrote the code, it always returns to the menu. Remove the loop and it won't return to the menu.

What's a loop? What does a loop do when it reaches the end of the loop? How does the loop stop?

As has been discussed in many other threads here, "cin >>" doesn't remove the end-of-line from the stream after you read in the zero or one. So I'm thinking the getline() at line 21 gets the now-empty line and writes it to the file, rather than waiting for a new line of input.

Instead of cin >> n1; at line 16, try:

#include <sstream>
...
string line;
getline(cin, line);
istringstream is_strm(line);
is_strm >> n1;

Naveen12,
Please do not add questions to solved threads. Instead, create a new thread, re-posting your code with any specific questions. Thanks!

This question has already been answered. Start a new discussion instead.