C++ 如何从文件中读取整行(带空格)?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15362367/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 19:18:35  来源:igfitidea点击:

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

c++filestliofstream

提问by Vladimir

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

我正在使用 STL。我需要从文本文件中读取行。如何阅读行直到第一个\n但不读到第一个' '(空格)?

For example, my text file contains:

例如,我的文本文件包含:

Hello world
Hey there

If I write like this:

如果我这样写:

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

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

thenstr将只包含“Hello”,但我需要“Hello world”(直到第一个\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.

我以为我可以使用该方法,getline()但它需要指定要读取的符号数。就我而言,我不知道应该阅读多少个符号。

回答by David Rodríguez - dribeas

You can use getline:

您可以使用 getline:

#include <string>
#include <iostream>

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

回答by user322

using getlinefunction is one option.

or

使用getline函数是一种选择。

或者

getcto read each char with a do-while loop

getc用 do-while 循环读取每个字符

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

如果您的文件由字符串组成,请尝试修改此方法。

回答by user633658

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.

对于 std::string,任何变量名称都可以,并且可以使用多长时间,无论您觉得合适还是使用 std::getline 如上所述。

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

要处理该行,只需在 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.

并逐个字符地处理迭代器指针,直到您拥有正在查找的 \n 和 ' '。

回答by Vladimir

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