Vladimir
Vladimir

Reputation: 117

How to read the whole lines from a file (with spaces)?

I am using STL. I need to read lines from a text file. How to read lines till the first \n but not till the first ' ' (space)?

For example, my text file contains:

Hello world
Hey there

If I write like this:

ifstream file("FileWithGreetings.txt");
string str("");
file >> str;

then str will contain only "Hello" but I need "Hello world" (till the first \n).

I thought I could use the method getline() but it demands to specify the number of symbols to be read. In my case, I do not know how many symbols I should read.

Upvotes: 5

Views: 32144

Answers (4)

Vladimir
Vladimir

Reputation: 117

Thanks to all of the people who answered me. I made new code for my program, which works:

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

using namespace std;

int main(int argc, char** argv)
{
    ifstream ifile(argv[1]);

    // ...

    while (!ifile.eof())
    {
        string line("");
        if (getline(ifile, line))
        {
            // the line is a whole line
        }

        // ...
    }

    ifile.close();

    return 0;
}

Upvotes: 2

user633658
user633658

Reputation: 2623

I suggest:

#include<fstream>

ifstream reader([filename], [ifstream::in or std::ios_base::in);

if(ifstream){ // confirm stream is in a good state
   while(!reader.eof()){
     reader.read(std::string, size_t how_long?);
     // Then process the std::string as described below
   }
}

For the std::string, any variable name will do, and for how long, whatever you feel appropriate or use std::getline as above.

To process the line, just use an iterator on the std::string:

std::string::iterator begin() & std::string::iterator end() 

and process the iterator pointer character by character until you have the \n and ' ' you are looking for.

Upvotes: 1

user322
user322

Reputation: 103

using getline function is one option.

or

getc to read each char with a do-while loop

if the file consists of numbers, this would be a better way to read.

do {
    int item=0, pos=0;
    c = getc(in);
    while((c >= '0') && (c <= '9')) {
      item *=10;
      item += int(c)-int('0');
      c = getc(in);
      pos++;
    } 
    if(pos) list.push_back(item);
  }while(c != '\n' && !feof(in));

try by modifying this method if your file consists of strings..

Upvotes: 2

You can use getline:

#include <string>
#include <iostream>

int main() {
   std::string line;
   if (getline(std::cin,line)) {
      // line is the whole line
   }
}

Upvotes: 10

Related Questions