文件未保存或不保存

File not saving, or not

本文关键字:保存 文件      更新时间:2023-10-16

我似乎无法弄清楚为什么,在底部的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");