我的程序总是停止工作:S (C++)
我编写了一个程序来从文件中获取数据,它可以工作,但是程序说它停止工作。 这是我的代码:
#include <stdio.h>
#include <windows.h>
#include <iostream>
using namespace std;
string show()
{
FILE *in;
char c;
in = fopen("version.txt", "r");
if(in != NULL)
{
while((c = fgetc(in)) != EOF)
{
putchar(c);
}
fclose(in);
}
else printf("Unable to open file\n");
}
int main()
{
show();
}
I made a program to get data from a file, it works, but then the program says it stopped working.
Here is my code:
#include <stdio.h>
#include <windows.h>
#include <iostream>
using namespace std;
string show()
{
FILE *in;
char c;
in = fopen("version.txt", "r");
if(in != NULL)
{
while((c = fgetc(in)) != EOF)
{
putchar(c);
}
fclose(in);
}
else printf("Unable to open file\n");
}
int main()
{
show();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您的函数被声明为返回一个
字符串
,但没有 return 语句。这是 C++ 中的“未定义行为”(仅在
main
中,您可以省略 return 语句,在这种情况下,C++ 将自动假定return 0;
- 但 IMO最好也总是写它)。Your function is declared to return a
string
but there is no return statement.This is "undefined behavior" in C++ (only in
main
you are allowed to omit the return statement and in that case C++ will assume areturn 0;
automatically - but IMO it's nicer to also always write it).fgetc man 说:
fgetc() 从流中读取下一个字符并将其作为
unsigned char 转换为 int
当循环到达文件末尾时,
fgetc
返回 EOF,它位于 int 上。当您将其转换为字符时,您的条件将始终返回 true。在测试其值是否为 EOF 之前,必须将 c 的类型更改为 int。fgetc man says:
fgetc() reads the next character from stream and returns it as an
unsigned char cast to an int
When your loop reaches the end of the file,
fgetc
returns EOF, which is on a int. As you cast it to a char, your condition will always return true. You must change the type of c to an int before testing if its value is EOF.您必须返回一些字符串,例如 return "";
问候。
You must return some string, for example return "";
Regards.
只需将
string show()
更改为void show()
即可。那会解决你的问题。Just change
string show()
tovoid show()
. That will solve your problem.这里有很多错误或模糊的事情。
首先:决定必须是 C 还是 C++。在 C++ 中,还有其他读取文件的方法(请参阅 std::fstream)
第二:删除不需要的标头。包括 stdio 和 iostream(它们产生类似的东西,一个用于 C,另一个用于 C++,意味着不清楚您实际想要做什么!)
第三:包括 windows.h 意味着编译所有 Windows API 声明。那是你根本没用过!这样做的目的是什么?
第四:
show
中string
的作用是什么? string 是 C++ 类型,在所有输入都用 C 编写的程序中。而且您没有返回任何内容!第五:
fgetc
返回 int。您很可能遇到EOF 陷阱。Lots of wrong or fuzzy things here.
First: decide if this has to be C or C++. In C++ there are other methods to read files (see
std::fstream
)Second: remove not needed headers. Including both stdio and iostream (that make similar things, one for C the other for C++, means having a non clear idea of what you're actually want to do!)
Third: including windows.h means compile all the windows API declarations. That you're not using at all! What was the purpose of that?
Fourth: What's the purpose to
string
inshow
? string is a C++ type, in a program where all input had been written in C. And you didn't return anything!Fifth:
fgetc
return as int. You're most likely running into the EOF pitflall.