我正在编码以创建我自己的 scanf
类型函数,当这个问题发生时。以下代码在控制台中测试时完美运行。
#include <stdio.h>
#include <stdlib.h>
inline void fastint(int &x){
register int c = getchar();
x = 0;
for(; ((c<48 || c>57) && c != '-'); c = getchar());
for(; c>47 && c<58 ; c = getchar()){
x = (x<<1) + (x<<3) + c - 48;
}
}
inline void faststring(char * arr){
register char c = getchar();
register int i = 0;
while (c < 33)
c = getchar();
while (c != '\n'){
arr[i] = c;
c = getchar();
i = i + 1;
}
arr[i] = '\0';
}
int main(){
int i;
char * arr = (char*)malloc(20*sizeof(char));
fastint(i);
printf("number is %d\n",i);
// fprintf(stderr, "new format %d\n", that_pesky_x);
fastint(i);
printf("number is %d\n",i);
fastint(i);
printf("number is %d\n",i);
fastint(i);
printf("number is %d\n",i);
fastint(i);
printf("number is %d\n",i);
faststring(arr);
printf("string is %c\n",arr[3]);
faststring(arr);
printf("string is %c\n",arr[3]);
faststring(arr);
printf("string is %c\n",arr[3]);
faststring(arr);
printf("string is %s\n",arr);
faststring(arr);
printf("string is %s\n",arr);
faststring(arr);
printf("string is %s\n",arr);
return 0;
}
但是当上面的代码在一个文本文件(名为input.txt)上测试时,其内容是:
12
32
12
42
343
hello dear
how is life
it is good man
Yes, it is the one
Have been search for this
Really, it is the only one
并尝试使用 windows 命令将输出保存到另一个文本文件 (output.txt)
new_scan.exe <input.txt> output.txt
在 Windows 中显示 new_scan.exe has stopped working
.
可能这是由于段错误造成的,但我无法弄清楚。请帮忙解决。
提前致谢!
最佳答案
首先,您需要增加数组大小,因为您的一些测试用例超过 20 个字节。
其次,因为您正在从文件中读取,所以您需要检查 EOF。 所以改变
while (c != '\n'){
// Do some work
}
到
while (c != '\n' && c != EOF){
// Do some work.
}
最后,您需要释放已分配的内存以进行良好实践。
现在您的代码应该可以正常工作了。
关于c++ - 为什么这显示运行时错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23514092/