4

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

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

Hello world
Hey there

如果我这样写:

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

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

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

4

4 回答 4

9

你可以使用getline:

#include <string>
#include <iostream>

int main() {
   std::string line;
   if (getline(std::cin,line)) {
      // line is the whole line
   }
}
于 2013-03-12T13:18:55.930 回答
2

使用getline功能是一种选择。

或者

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

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

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

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

于 2013-03-12T13:31:30.040 回答
2

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

#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;
}
于 2013-03-12T13:41:52.033 回答
1

我建议:

#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 和 ' '。

于 2013-03-12T13:33:24.300 回答