【发布时间】:2020-05-26 18:44:27
【问题描述】:
我有这段代码,但是从命令行输入名称后它开始工作,但输出是一个永无止境的奇怪字符数组。 我试图提出的问题是:编写一个使用 read() 方法读取文件内容的 C++ 应用程序。获得的数据显示在屏幕上。每次读取操作后检查系统状态。文件名是从命令行读取的。 我的代码是:
#include<iostream>
#include<fstream>
using namespace std;
int main(int argc, char* argv[])
{
char arr[15];
ifstream file;
file.open(argv[1], ios::in); //filename read from the command line
if (argc == 1)
{
cout << "Enter file name from command line!";
}
int readState = 0;
while (!file.eof())
{
file.read(arr, 10); //reading the file's content
if (file.good())
{
arr[10] = '\0';
cout << arr;
readState++; //checking the system's state after each read()
}
else
{
cout << arr;
}
}
file.close();
return 0;
}
我也检查了,文件没有创建.. 如果您有任何提示如何纠正它或我如何以其他方式制作它会有所帮助..
【问题讨论】:
-
如果
file.good()为假,您将尝试打印一个非空终止的字符串... -
@NateEldredge 我试图在那里显示一条简单的消息,输出是一样的..
-
并且您总是在数组中的第十个字符之后终止,而不是查看读取的实际字符数。文件内容是否至少 10 个字符,且长度为 10 个字符的倍数?
-
不管你应该修复那个错误。它迟早会得到你。
-
注意:文件以某种不是 EOF 的方式失败,你有一个无限循环。很难处理未格式化的读取,但仍然值得为自己辩护。
标签: c++ file command-line