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

删除回忆录丶 提交于 2019-12-23 20:08:11

问题


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.


回答1:


You can use getline:

#include <string>
#include <iostream>

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



回答2:


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..




回答3:


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.




回答4:


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;
}


来源:https://stackoverflow.com/questions/15362367/how-to-read-the-whole-lines-from-a-file-with-spaces

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!