Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
252 views
in Technique[技术] by (71.8m points)

c++ - Read File line by line to variable and loop

I have a phone.txt like:

09236235965
09236238566
09238434444
09202645965
09236284567
09236235965
..and so on..

How can I process this data line by line in C++ and add it to a variable.

string phonenum;

I know I have to open the file, but after doing so, what is done to access the next line of the file?

ofstream myfile;
myfile.open ("phone.txt");

and also about the variable, the process will be looped, it will make the phonenum variable the current line its processing from the phone.txt.

Like if the first line is read phonenum is the first line, process everything and loop; now the phonenum is the 2nd line, process everything and loop until the end of the last line of the file.

Please help. I'm really new to C++. Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Read the comments inline please. They will explain what is going on to assist you in learning how this works (hopefully):

#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>

int main(int argc, char *argv[])
{
    // open the file if present, in read mode.
    std::ifstream fs("phone.txt");
    if (fs.is_open())
    {
        // variable used to extract strings one by one.
        std::string phonenum;

        // extract a string from the input, skipping whitespace
        //  including newlines, tabs, form-feeds, etc. when this
        //  no longer works (eof or bad file, take your pick) the
        //  expression will return false
        while (fs >> phonenum)
        {
            // use your phonenum string here.
            std::cout << phonenum << '
';
        }

        // close the file.
        fs.close();
    }

    return EXIT_SUCCESS;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...