c++ - 为什么这显示运行时错误?

标签 c++ c

我正在编码以创建我自己的 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/

相关文章:

c++ - 为什么当您尝试使用 arr = {values} 为数组赋值时会发生错误?

c - 如何计算像: '10+2-4/2' 这样的算术表达式

c - 在C中生成随机数并将其写入文本文件

c++ - 如何从 Lua 上下文中卸载代码

c++ - 为什么模板参数包必须在最后?

c++ - BOOST_DATA_TEST_CASE是否始终要求 sample 的可打印性?

c++ - 构造函数定义

c - 如何读取 PowerShell 标准输出

c - 结构体和指针

c - 宏如何返回指向未对齐值的对齐指针?