简体   繁体   中英

How to read a file having multiple lines, line by line in C++?

I am trying to read a file having multiple lines, where each line has a word and then a space followed by a short description of the word.

Example of the text file:

hello A type of greeting
clock A device which tells us the time
.

The fullstop (.) at the end represents that there are no more lines to read.

I tried an approach using a delimiter in the getline() function, but only succeeded in reading one line of the file. I want to store the first word (before the first space) in a variable, say word , and the description (words after the first space until a new line character is encountered) in another variable, say desc .

My approach:

#include <iostream>
#include <fstream>
#include <string.h>

using namespace std;

int main()
{
    string filename = "text.txt" ;
    ifstream file (filename);
    if (!file)
    {
        cout<<"could not find/open file "<<filename<<"\n";
        return 0;
    } 

    string word;
    string desc;
    string line;


    while(file){
        getline(file,line,' ');
        
        word = line;
        break;
    }
    while(file){
        getline(file,line,'\n');
        desc = line;
        break;
    }    

   file.close();
    cout<<word<<":  ";
    cout<<desc<<"\n";

    return 0;
}

The output of the above code is:

hello:  A type of greeting

I tried adding another parent while loop to the ones written above, having the condition file.eof() , but then the program never enters the two child loops.

You don't need multiple loops, a single loop will suffice. Read a line, and then use a std::istringstream to split it as needed. Repeat for each line.

For example:

#include <iostream>
#include <fstream>
#include <sstream>
#include <string>

using namespace std;

int main()
{
    string filename = "text.txt";
    ifstream file (filename);
    if (!file)
    {
        cout << "could not find/open file " << filename << "\n";
        return 0;
    } 

    string word;
    string desc;
    string line;

    while (getline(file, line) && (line != ".")) {
        istringstream iss(line);
        iss >> word;
        getline(iss, desc);
        cout << word << ":  " << desc << "\n";
    }

    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM