ifstream get() 不填充字符数组

ifstream get() not filling char array

本文关键字:填充 字符 数组 get ifstream      更新时间:2023-10-16

我不知道会做什么

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

与测试.yaml 是这个

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

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

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

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

这解决了眼前的问题,但使用std::getlinestd::string会更好C++。像这样:

while(std::getline(readt1, line)) {// Do stuff}

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

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