CodeBlocks exe 停止工作

标签 c arrays char strcmp

#include <stdio.h>
#include <stdlib.h>
#include<string.h>
int main()
{
    char string;
    printf("Hello\n");
    printf("What would you like to do\n");
    printf("Here are the options\n");
    printf("s : How are you\n");
    printf("c : What would you like to search\n");
    scanf("%s",&string);
    if(string == 'h')
        printf("iam fine\n");

    else if (string == 's')
        printf("What would you like to search\n");
    scanf("%s",&string);
    system(string);
    return 0;
}

当我在它说你想搜索什么后运行它并且我输入 run notepad 它停止工作。

最佳答案

此 scanf 有两个问题:

printf("What would you like to search\n");
scanf("%s",&string);
system(string);
  1. string 是单个字符 - scanf 将导致缓冲区溢出。

  2. %s 格式说明符仅读取到下一个空格。

要解决此问题,您应该分配更大的缓冲区并读取整行:

char buffer[1024];
printf("What would you like to search\n");
fgets(buffer, sizeof buffer, stdin);
system(buffer);

关于CodeBlocks exe 停止工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28943987/

相关文章:

c - 在迷你过滤器驱动程序中使用 GetProcessImageFileName

PHP:如果在多维数组中发现重复项,则合并相邻值

arrays - 以最少的移动次数对数组进行排序

swift - 访问字符串中的字符,Swift 3.x

c - 指向多维数组的指针

C 数组声明语法

c++ - 了解 FPS 及其使用的方法

c - 如何将字符串标记输入二维数组?

c - 将 char 数组传递给 (void const *p)

Java 隐式将整数转换为 ASCII 字符 A-F