gpt4 book ai didi

c++ - 无法正确输出文件

转载 作者:行者123 更新时间:2023-11-28 02:23:01 26 4
gpt4 key购买 nike

我正在编写这个非常简单的程序,它使用文件输出 hello world。请记住,我希望 hello 和 world 位于不同的行上。

代码如下:

    int main()
{


std::ofstream someFile("file.dat");
someFile << "" << std::endl;

std::fstream someOtherFile("file.dat",ios::in | ios::out);

std::string content;

someOtherFile << "hello" << std::endl;
someOtherFile << "world" << std::endl;
someOtherFile.seekg(0, ios::beg);
std::getline(someOtherFile, content);
std::cout << content << std::endl;
return 0;


}

但是,每当我运行以下程序时,它只打印“hello”。

任何帮助将不胜感激,请给出一个使用 fstream 的示例,而不是 ofstream 或 ifstream(我正在尝试学习 fstream 的工作原理,但我发现了一点麻烦)。

我的编译器是最新的VS。

最佳答案

getine函数一次只读一行,所以你应该调用getline直到文件结束。下面的代码可以帮助您。

#include <iostream>
#include <fstream>`
#include <string>
using namespace std;
int main()
{


std::ofstream someFile("file.dat");
someFile << "" << std::endl;

std::fstream someOtherFile("file.dat",ios::in | ios::out);

std::string content;

someOtherFile << "hello" << std::endl;
someOtherFile << "world" << std::endl;
someOtherFile.seekg(0, ios::beg);
while(std::getline(someOtherFile, content))
{

std::cout << content << std::endl;
}

return 0;
}

关于c++ - 无法正确输出文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31690455/

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