1

我不知道该怎么做

#include "fstream"
#include "iostream"

using namespace std;

#define out(a) cout << #a << ": " << a << '\n'

void print(string s)
{
  cout << s << '\n';
}

 int main()
{
  ifstream readt1;
  readt1.open("test1.yaml");

  while(readt1.good())
  {
    char cc[128];
    readt1.get(cc,128);
    out(cc);
  }
readt1.close();
}

该代码...输出:

cc: version: 0.14.1
cc: 

test.yaml 就是这个

version: 0.14.1
name: scrumbleship
author: dirkson
description: >
  A minecraft like game that allows you
  to build your own spaceship!

我已经尝试了很多方法来让它工作,但它根本没有

4

3 回答 3

2

如果readt1.ignore();在 get() 之后添加 a 它应该可以工作:

  while(readt1.good())
  {
    char cc[128];
    readt1.get(cc,128);
    readt1.ignore(); // <--- add this to ignore newline
    out(cc);
  }

这解决了眼前的问题,但使用std::getlineC std::string++ 会更好。就像是:

while(std::getline(readt1, line)) {// Do stuff}
于 2012-05-21T05:32:21.763 回答
1

您应该使用getline()通过 ifstream 读取行

于 2012-05-21T05:27:04.757 回答
0

另外,我会在循环之外获取第一行,并且循环应该检查 EOF 以确保您获得整个文件。good() 不只是暗示有要读取的文件吗?

于 2012-05-21T05:29:32.100 回答