繁体   English   中英

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

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

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

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

Hello world
Hey there

如果我这样写:

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

然后str将只包含“Hello”但我需要“Hello world”(直到第一个\\n )。

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

你可以使用getline:

#include <string>
#include <iostream>

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

使用getline函数是一种选择。

要么

getc用do-while循环读取每个char

如果文件由数字组成,这将是一种更好的阅读方式。

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

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

我建议:

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

对于std :: string,任何变量名都可以,多长时间,无论你觉得合适,或者如上所述使用std :: getline。

要处理该行,只需在std :: string上使用迭代器:

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

并按字符处理迭代器指针,直到你有\\ n和''你正在寻找。

感谢所有回答我的人。 我为我的程序创建了新代码,该代码有效:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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