无法正确输出文件

时间:2015-07-29 02:50:06

标签: c++ visual-c++ fstream

我正在编写这个非常简单的程序,它使用文件来解决问题世界。请记住,我希望你好和世界分开。

这是以下代码:

    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;


       }

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

任何帮助将不胜感激,请举例说明使用fstream,而不是ofstream或ifstream(我正在尝试了解fstream如何工作,但是我发现有点麻烦)。

我的编译器是最新的VS。

5 个答案:

答案 0 :(得分:1)

您有两行代码:

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

他们将2行字符串放入file.dat:

// file.dat
hello
world

功能&#34; getline()&#34;从文件中只获得一行。 &#34; seekg&#34;函数将读取位置设置为文件的第一行:其中包含&#34; hello&#34;。

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

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

使用:

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

如果您只想要特定的行,请使用计数器变量。

顺便说一句,我只是假设你打算把变量&#34; content&#34;在哪里&#34;名称&#34;是

答案 1 :(得分:1)

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;
}

答案 2 :(得分:0)

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

  

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

     

is中提取字符并将其存储到str中,直到找到分隔字符分隔符(或换行符,'\ n',(2))。

答案 3 :(得分:0)

在第一组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只获取文件中的一行。要获得下一行,您需要再次拨打电话。

答案 4 :(得分:0)

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


       }

这将打印您想要的答案

相关问题