文件未保存或不保存
File not saving, or not
我似乎无法弄清楚为什么,在底部的while循环中,
std::cout << line;
不打印任何内容。
我相信 test.txt 文件实际上并没有被写入,因为当我在我的文件夹中打开 test .txt 时,它是空的。有什么想法吗?
void Ticket::WriteTicket()
{
std::string ticketInput;
std::ofstream ticketFile("test.txt");
ticketFile.open("test.txt");
std::cout << "Please Enter Ticket Information: " << std::endl;
getline(std::cin, ticketInput);
std::cout << ticketInput << std::endl; //does print out the line
ticketFile << ticketInput;
ticketFile.close();
//here for testing only
std::string line;
std::ifstream ticketRead("test.txt");
while(getline(ticketRead, line));
{
std::cout << "something here?: " << line; // there is nothing here when it outputs
}
}
编辑(解决方案):
在使用上面给出的一些信息后,主要来自Basile Starynkevitch(我把它放在这里是因为我还不能投票),我能够让代码工作!
我还在我的书中做了一些研究,并复制了类似程序的风格。也就是在哪里放置代码的哪一部分,然后输入工作。我继续输出,关键部分是打开文件进行输出时的std::ifstream::in
。
void Ticket::WriteTicket()
{
std::string ticketInput;
std::cout << "Please Enter Ticket Information: " << std::endl;
getline(std::cin, ticketInput);
std::ofstream ticketFile("Ticket.txt");
ticketFile << ticketInput << std::endl;
ticketFile.close();
//here for testing
std::ifstream ticketRead;
ticketRead.open("Ticket.txt", std::ifstream::in);
std::string line;
while(getline(ticketRead, line))
{
std::cout << line << std::endl;
}
}
谢谢大家的帮助!
您需要刷新输出缓冲区。
ticketFile << ticketInput;
应该是
ticketFile << ticketInput << std::endl;
std::endl 刷新输出缓冲区。请参阅 std::flush 如果您不想要新行。
C++ I/O 被缓冲。至少代码
std::cout << "something here?: " << line << std::flush;
但在你的情况下
std::cout << "something here?: " << line << std::endl;
会更好。
也
std::ofstream ticketFile("test.txt")
应该是
std::ofstream ticketFile("test.txt", std::ios_base::out);
我强烈建议在编码之前花一些时间阅读有关C++库的更多信息。检查您正在使用的每个函数或类。当然,您还需要 std::flush on ticketFile
.
也许文件需要在写入模式下打开。试试这个 std::ofstream ticketFile("test.txt","w");
相关文章:
- 保存文件并使控制台不关闭:Visual Studio 2019
- 将值更改为 c++ 的数组并保存文件
- 如何保存文件中的所有数据?C++
- 更改代码::块上的默认保存文件类型
- 使用setW()函数保存文件时,如何获取每个属性的值
- 尝试使用 ostream 保存文件内容时出错
- 如何使用3d的max 2016 SDK(C++)在插件中添加保存文件对话框?
- 如何在不保存文件的情况下制作打印屏幕并将其发送到FTP服务器?我的工作代码将文件保存到HDD
- 视频编写器功能不会使用 OpenCV-3.0.0 保存文件
- 使用fstream明确保存文件,而无需在C 中关闭文件
- 位换档字符串以解码保存文件C
- QFile在程序退出时保存文件,根本不会保存~500MB文件
- 保存文件或文件夹的时间戳
- Fstream不会保存文件中的最后一个单词,也不会从文件中读取
- CFileDialog保存文件的名称为空
- 如何以正确的编码保存文件
- 在动态分配的 char 数组中保存文件的类内容
- 如何在win32中使用GetSave文件名保存文件
- 覆盖保存文件的非常安全的方法
- 除非先使用MS Paint打开/保存文件,否则带有QRCode位图的LoadImage()将失败