使用 CIN COUT 显示垃圾值的文件对象?

file object showing garbage value using cin cout?

本文关键字:文件 对象 CIN COUT 显示 使用      更新时间:2023-10-16
#include<iostream.h>
#include<conio.h>
#include<fstream.h>
void main()
{
int i, j, k;
clrscr();
ofstream out("INT.TST");
ifstream in("INT.TST");
out << 25 << ' ' << 4567 << ' ' << 8910;
in >> i >> j >> k;
cout << i << ' ' << j << ' ' << k;
getch();
}

该程序的输出应为:

25 567 8910

但它显示在这里:

8370 0 1530

为什么它显示垃圾值?

我在 gcc 和 msvc 中测试了类似的代码,它在 Ubuntu 或 Windows 中按预期工作。我相信您没有创建或打开文件的权限(例如 ideone.com 等在线编译器(。因为您尚未检查文件是否已打开(使用is_open()(,您可能正在使用关闭的文件和不可预知的结果。请参阅以下代码:

#include <iostream>
#include <fstream>
using namespace std;
int main()
{
int i, j, k;
ofstream out("INT.TST");
ifstream in("INT.TST");
out << 25 << ' ' << 4567 << ' ' << 8910;
out.flush();
if (!in.is_open())
{
std::cout << "Error opening file";
}
else
{
in >> i >> j >> k;
cout << i << ' ' << j << ' ' << k;
}
return 0;
}

它用 ideone 编写Error opening file,但它可以像你预期的那样在 Ubuntu 和 Windows 上运行。

你的代码可能会被最近的(体面的?(编译器窒息,因为你打开同一个文件两次,一次用于读取,一次用于写入。这在 Windows 上通常是不允许的,除非将特殊值传递给基础 WinAPI 调用。由于 Turbo-C++ 已被弃用了几十年,我不确定当它无法打开文件或只是为您提供封闭流时它是否会引发异常。所以你应该始终控制输入函数!

代码的或多或少的固定版本可能是:

#include<iostream.h>
#include<conio.h>           // avoid if you can: non portable
#include<fstream.h>
int main()                  // NEVER use void main!
{
int i, j, k;
clrscr();               // avoid if you can: non portable
ofstream out("INT.TST");
out << 25 << ' ' << 4567 << ' ' << 8910;
out.close()             // Ok, file is now closed
ifstream in("INT.TST");
in >> i >> j >> k;
if (! in) {
cerr << "Error reading filen";
}
else {
cout << i << ' ' << j << ' ' << k;
}
getch();              // avoid if you can: non portable
return 0;             // not strictly necessary but IMHO cleaner
}