How to read and write to a text file in C++?

后端 未结 4 702
野趣味
野趣味 2020-12-14 02:24

Hey everyone, I have just started to learn C++ and I wanted to know how to read and write to a text file. I have seen many examples but they have all been hard to understand

4条回答
  •  眼角桃花
    2020-12-14 02:52

    Default c++ mechanism for file IO is called streams. Streams can be of three flavors: input, output and inputoutput. Input streams act like sources of data. To read data from an input stream you use >> operator:

    istream >> my_variable; //This code will read a value from stream into your variable.
    

    Operator >> acts different for different types. If in the example above my_variable was an int, then a number will be read from the strem, if my_variable was a string, then a word would be read, etc. You can read more then one value from the stream by writing istream >> a >> b >> c; where a, b and c would be your variables.

    Output streams act like sink to which you can write your data. To write your data to a stream, use << operator.

    ostream << my_variable; //This code will write a value from your variable into stream.
    

    As with input streams, you can write several values to the stream by writing something like this:

    ostream << a << b << c;
    

    Obviously inputoutput streams can act as both.

    In your code sample you use cout and cin stream objects. cout stands for console-output and cin for console-input. Those are predefined streams for interacting with default console.

    To interact with files, you need to use ifstream and ofstream types. Similar to cin and cout, ifstream stands for input-file-stream and ofstream stands for output-file-stream.

    Your code might look like this:

    #include 
    #include 
    
    using namespace std;
    
    int start()
    {
        cout << "Welcome...";
    
        // do fancy stuff
    
        return 0;
    }
    
    int main ()
    {
        string usreq, usr, yn, usrenter;
    
        cout << "Is this your first time using TEST" << endl;
        cin >> yn;
        if (yn == "y")
        {
            ifstream iusrfile;
            ofstream ousrfile;
            iusrfile.open("usrfile.txt");
            iusrfile >> usr;
            cout << iusrfile; // I'm not sure what are you trying to do here, perhaps print iusrfile contents?
            iusrfile.close();
            cout << "Please type your Username. \n";
            cin >> usrenter;
            if (usrenter == usr)
            {
                start ();
            }
        }
        else
        {
            cout << "THAT IS NOT A REGISTERED USERNAME.";
        }
    
        return 0;
    }
    

    For further reading you might want to look at c++ I/O reference

提交回复
热议问题