从显示垃圾的文件检索的字符串

Strings retrieved from files displaying garbage

本文关键字:文件 字符串 检索 显示      更新时间:2023-10-16

我有 2 个文件,easyp.txteasyn.txt ,分别easyp.txt存储点,easyn.txt存储名称。我有显示最高分和玩家姓名的代码。它工作正常,然后我编辑了一些其他行,再次运行时,它会喷出垃圾。代码如下所示:

case 1:
        infile.open("easyn.txt", ios::out | ios::app);
        ofile.open("easyp.txt", ios::out | ios::app);
        while (getline(infile, STRINGT) && getline(ofile, STRINGO))
        {
            istringstream buffer(STRINGO);
            buffer >> value;
            if (infile.eof() && ofile.eof()){
                printf("The top player for easy is %s with only %i tries!", STRINGD, value);
                break;
            }
            if (value < best)
            {
                STRINGD = STRINGT;
                best = value;
            }
        }
        infile.close();
        ofile.close();
        _getch();
        break;

(顺便说一句,点数越少越好)

当我运行程序时,它会输出随机的 ascii 字符作为玩家名称,1835884884作为分数。

是的,我using namespace std

我唯一一次有文件读取/写入是在以下情况下:

            ofstream myfile;
            myfile.open("easyn.txt", ios::out | ios::app);
            if (myfile.is_open())
            {
                myfile << chName << "n";
                myfile.close();
            }
            myfile.open("easyp.txt", ios::out | ios::app);
            if (myfile.is_open())
            {
                myfile << iTurns << "n";
                myfile.close();
            }

感谢您的帮助

程序的主要问题是:

printf("The top player for easy is %s with only %i tries!", STRINGD, value);

printf%s格式说明符期望的是char *,而不是std::string。您要解决此问题的是 用STRINGD.c_str()替换STRINGD .

将参数传递给函数预期接收的其他类型的 varargs 函数会调用未定义的行为。确切的情况取决于您的架构和 ABI,因此如果没有这些细节,我无法对此进行详细解释,但我认为这并不重要。:)

我不知道

这是否有帮助,但不要使用 .txt 扩展,而是使用 .dat 扩展。也许它会有所帮助?

.dat文件"data files"可以通过文本编辑器打开,所以我认为这可能会对>_有所帮助>

我会尽量不使用ios::out | ios::app,即使你确实使用它们,你做错了。 如果您想修复该教程,请查看此处 -> fileStreaming C++,主要是因为在大多数情况下您会使用 ios::out | ios::in

除了我个人之外,你还可以使用其他东西while (getline(infile, STRINGT) && getline(ofile, STRINGO))我永远不会使用它,主要是因为这只是我的偏好。