Click here to Skip to main content
15,887,849 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi. I wanted to learn about reading and writing files in C++. To understand it better I wrote the code below. The code below allows a user to create their own text file. After that, they can write information in it. Lastly, the contents of the file will be printed on the console.

Here is the problem: the code will allow a user create a text file but will not allow them to type anything into the file. Also, because the program stops after the line that says "please enter text:" (keep in mind that the program will not allow user to type anything at this point), I does not run the last part of the code which is to read what was in the file.

One thing I noticed was that if I cut out the part of the code that allows the user to write the file name (what I mean is that I put a default file name instead of allowing the user to type in their own file name) then the code works. However, I want to give the user the option of making their own file an writing in it so I don't see why this version won't work.

I have not been able to find information about this so I wanted to know if anyone on "codeproject.com" could help me. Thanks.

What I have tried:

C++
#include <iostream>
#include <fstream>
#include <sstream>
#include <string> 
using namespace std;
int main()
{
    cout << "Type in file name followed by the extention \".txt\"" << endl;
    string user_file;
    cin >> user_file;
    fstream file; //object of fstream class

    file.open(user_file, ios::out);
    if (!file)
    {
         cout << "File could not open" << endl;
         return 0;
    }
    cout << "File created." << endl;

    //write text into file
    char user_input[256];
    cout << "Please enter text: \n";
    std::cin.getline(user_input, 256);
    file << user_input;

    //cout << "For testing. User input is: " + user_input<< endl;
    file.close();//close the file
    system("pause");

    //open file to be read
    file.open(user_file, ios::in);
    if (!file)
    {
        cout << "File could not open" << endl;
        return 0;
    }
    cout << "Information in file: ";
    std::string line_;
    if (file.is_open())
    {
        while (getline(file, line_))
        {
            std::cout << line_ << endl;
        }
        file.close();
        std::cin.get();//for testing: will pause the screen
    }

    return 0;
}
Posted
Updated 17-Dec-19 14:39pm

I don't see a problem in the code immediately. Therefore, I have a suggestion for you. Comment off all of the code that prompts and acquires input and do all of that yourself with pseudo-random values. What I mean is come up with the name of a file by yourself and use that. Open the file as you normally would but write five or ten lines of text into it. Something along the lines of "this is message number X". Then close the file, delay for about a second, open the file for reading, and read and output all of the text you find in the file. This will verify your grasp of the mechanics of handling files. Once you have that perfected then uncomment the code that asks for user-input and try your same code with the strings entered by the user.

The key here is to isolate the issues and work on one thing at a time. In your case, your two issues are acquiring user input and handling the files. I find it much easier to tackle one issue at a time when ever possible and then verify the interaction of the components.

One other thing - see your string user_input and then the getline function call? Do you see what they have in common?

That is a bad thing. If you need a fixed-sized buffer, meaning you can't use a string object, then first define a constant for the maximum size of the string. Then declare your character buffer with a size one larger so you have room for the terminating null character, and then use that constant in the getline call. Here is what that code would like with a maximum size of 255 characters:
C++
const size_t bufferSize = 255;
char user_input[ bufferSize + 1 ] = { 0 };
std::cin.getline( user_input, bufferSize );
This way the input can never exceed the size of the buffer and it will always be null-terminated. Also, if you want to change the size of the buffer you do it only one place. That is the primary goal of this tactic.

I noticed you use a string object to read the file in so you should be able to use one to acquire input from the user also and then the above stuff will be unnecessary.

If you find your program is not working for some reason the best way to find out why is to use the debugger. It is an incredibly important tool and one you should strive to learn. If your development environment does not have a debugger then you should find an alternative that does if at all possible. Without one you're essentially flying blind.
 
Share this answer
 
Thank you for the added information. I see what you mean. I guess I need to learn how to use my debugger. Also, because I am still a college student learning about coding I did not know you could put constraints in your code! I though that only applies to Databases (Ex: writing constraints for a table values). I will try to remember that for next time. Lastly, I sat and worked on it all day and this turns out to be the solution (meaning I finally got it to work). I read something about the ".get()" keyword so I switched to that and it seemed to work. I will post it in case it could help someone else out:

C++
#include <iostream>
#include <fstream>
#include <sstream>
#include <string> 
using namespace std;
int main()
{
    cout << "Type in a file name followed by the extention \".txt\"" << endl;
    string user_file;
    getline(cin, user_file);
    fstream file; //object of fstream class
   //opening file "sample.txt" in out(write) mode
    file.open(user_file, ios::out);
    if (!file)
    {
        cout << "Could not open file" << endl;
        return 0;
    }
    cout << "File created." << endl;
    //write text into file
    string user_input;
    cout << "Please enter text: \n";
    getline(cin, user_input);
    file << user_input << endl;
    //cout << "For testing. User input is: " + user_input<< endl;
    file.close();//close the file
    
    //open file to be read
    file.open(user_file, ios::in);
    if (!file)
    {
        cout << "Could not open file" << endl;
        return 0;
    }
    char ch; //read character
    cout << "File Information: ";
    while (true)
    {
        file.get(ch);
        if (file.eof())break;
        cout << ch;
    }
    
    file.close();

    cout << "Lets find a file and open it" << endl;
    cout << "Type the name of the file followed by it's the extention \".txt\": " << endl;
    string find_user_file;
    getline(cin, find_user_file);

    //open file to be read
    file.open(find_user_file, ios::in);
    if (!file)
    {
        cout << "Could not open file" << endl;
        return 0;
    }
    char ch2; //read character
    cout << "File Information: ";
    while (true)
    {
        file.get(ch2);
        if (file.eof())break;
        cout << ch2;
    }
    file.close();
    system("pause");
    return 0;
}
 
Share this answer
 
Comments
Patrice T 17-Dec-19 21:02pm    
Use Improve question to update your question.
Avoid using a solution
tara lara 17-Dec-19 21:10pm    
Ok. I'll do that. Sorry. I never use this website therefore I didn't know about that.
Patrice T 17-Dec-19 21:17pm    
you're welcome :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900