954,498 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

DEV-C++ file input and output problems

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?

thecoolman5
Posting Whiz in Training
234 posts since Dec 2010
Reputation Points: 18
Solved Threads: 1
 

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

WaltP
Posting Sage w/ dash of thyme
Moderator
10,506 posts since May 2006
Reputation Points: 3,348
Solved Threads: 944
 

How is the loop causing the problem?

thecoolman5
Posting Whiz in Training
234 posts since Dec 2010
Reputation Points: 18
Solved Threads: 1
 

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

WaltP
Posting Sage w/ dash of thyme
Moderator
10,506 posts since May 2006
Reputation Points: 3,348
Solved Threads: 944
 

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;
raptr_dflo
Practically a Master Poster
602 posts since Aug 2010
Reputation Points: 76
Solved Threads: 82
 

ok it works. thanks

thecoolman5
Posting Whiz in Training
234 posts since Dec 2010
Reputation Points: 18
Solved Threads: 1
 

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

Naveen12
Newbie Poster
1 post since Jun 2011
Reputation Points: 10
Solved Threads: 0
 

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

raptr_dflo
Practically a Master Poster
602 posts since Aug 2010
Reputation Points: 76
Solved Threads: 82
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: