从显示垃圾的文件检索的字符串
Strings retrieved from files displaying garbage
我有 2 个文件,easyp.txt
和 easyn.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))
我永远不会使用它,主要是因为这只是我的偏好。
- 将字符指针十六进制转换为字符串并保存在文本文件C++中
- 有没有办法从非C/C++文件中读取C++原始字符串文字的内容
- 如何打开并写入一个名称取自C++中字符串的文件
- 如何从二进制文件中读取字符串
- 如何在 c++ 中使用 getline 从文件中读取字符串?
- 将字符串与文件上的数据进行比较
- 用户输入字符串的文件附加问题..C++
- 如何从文件中读取两个字符串和数字数组,并将它们存储在对象向量中
- 如何使字符串出现在编译的二进制可执行文件的开头?
- 使用文件内容作为硬编码字符串
- 将文件复制到自定义位置,存在字符串转换问题
- 在 c++ 中连接字符串和整数,以便在 C++ 11 不支持计算机的情况下读取多个文件
- 声明要在 qml 和 cpp 文件中使用的全局字符串
- C 通过char读取文件字符串的文件char;崩溃
- 我不明白如何将 toupper 和 isalpha 与.txt文件字符串输入一起使用
- 在 CPP 文件中使用 make 文件字符串变量
- 编译 PyGAMMA Mac Lion:g++ 找不到标准的 C++ 头文件(字符串/iostream..)
- 如何在c++中使用文件字符串作为命令
- 使用 TinyXML 解析 XML 文件字符串
- 递归下降解析器帮助(不读取文本文件字符串)