Read File line by line to variable and loop

前端 未结 3 1957
旧时难觅i
旧时难觅i 2021-01-06 00:59

I have a phone.txt like:

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

How can I process this data

相关标签:
3条回答
  • 2021-01-06 01:21

    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 << '\n';
            }
    
            // close the file.
            fs.close();
        }
    
        return EXIT_SUCCESS;
    }
    
    0 讨论(0)
  • 2021-01-06 01:36

    Simple. First, note that you want an ifstream, not an ofstream. When you're reading from a file, you're using it as input - hence the i in ifstream. You then want to loop, using std::getline to fetch a line from the file and process it:

    std::ifstream file("phone.txt");
    std::string phonenum;
    while (std::getline(file, phonenum)) {
      // Process phonenum here
      std::cout << phonenum << std::endl; // Print the phone number out, for example
    }
    

    The reason why std::getline is the while loop condition is because it checks the status of the stream. If std::getline fails in anyway (at the end of your file, for example), the loop will end.

    0 讨论(0)
  • 2021-01-06 01:38

    You can do that :

     #include <fstream>
     using namespace std;
    
     ifstream input("phone.txt");
    
    for( string line; getline( input, line ); )
    {
      //code
    }
    
    0 讨论(0)
提交回复
热议问题