gpt4 book ai didi

c++ - ifstream get() 不填充字符数组

转载 作者:行者123 更新时间:2023-11-30 03:01:51 26 4
gpt4 key购买 nike

我不知道要做什么

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

我已经尝试了很多方法来让它工作,但它就是行不通

最佳答案

如果您在 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}

关于c++ - ifstream get() 不填充字符数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10679839/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com