无法正确输出文件

can't get file to output correctly

本文关键字:输出 文件      更新时间:2023-10-16

我正在编写一个非常简单的程序,它使用文件来组织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;
}

您有两行代码:

someOtherFile << "hello" << std::endl;
someOtherFile << "world" << std::endl;

他们将两行字符串放入文件.dat:

// file.dat
hello
world

函数"getline(("只从文件中获取1行。"seekg"函数将读取位置设置为文件的第一行:其中包含"hello"。

如果你想读到文件的末尾:然后替换:

std::getline(someOtherFile, content);
std::cout << content << std::endl;

带有:

while (!someOtherFile.eof())
{
    std::getline(someOtherFile, content);
    std::cout << content << std::endl;
}

如果只需要特定的行,也可以使用计数器变量。

顺便说一句,我只是假设你想把变量"content"放在"name"所在的地方。

std::getline只从特定文件中获取一行文本。像http://www.cplusplus.com/reference/string/string/getline/?kw=getline说:

istream& getline (istream& is, string& str);

is中提取字符并将其存储到str中,直到找到定界字符delim(或换行符'\n',表示(2((。

在第一组getline和cout之后添加另一个getline(..(和cout语句。你会得到世界作为输出。

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

getline只获取文件中的一行。要接下一个电话,你需要再打一次。

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

        std::ofstream someFile("file.dat");
        someFile << "" << std::endl;
        someFile.close();
        std::fstream someOtherFile("file.dat",ios::in | ios::out);
        std::string content;
        someOtherFile << "hello ";
        someOtherFile << "world" << std::endl;
        someOtherFile.close();
        someOtherFile.seekg(0, ios::beg);
        std::getline(someFile1, content);
        std::cout << content << std::endl;
        someFile1.close();
        return 0;

       }

这将打印您想要的答案