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?

Recommended Answers

All 7 Replies

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

How is the loop causing the problem?

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;

ok it works. thanks

how to add a new line in between the program for the above

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.