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

Strings retrieved from files displaying garbage

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

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

我唯一一次拥有文件 reading/writing 的时间如下:

            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 替换为 STRINGD.c_str().

将参数传递给不同于函数预期接收的另一种类型的可变参数函数会调用未定义的行为。究竟会发生什么取决于您的体系结构和 ABI,所以如果没有这些细节,我真的无法给出详细的解释,但我认为这并不重要。 :)

我不知道这是否有帮助,但不要使用 .txt 扩展名,而是使用 .dat 扩展名。也许会有帮助?

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

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

除了 while (getline(infile, STRINGT) && getline(ofile, STRINGO)) 个人之外,您还可以使用其他东西我从来没有使用过它,主要是因为它只是我的偏好。