【问题标题】:CodeBlocks exe stops workingCodeBlocks exe 停止工作
【发布时间】:2015-03-09 14:07:03
【问题描述】:
#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 它停止工作。

【问题讨论】:

    标签: c arrays char strcmp


    【解决方案1】:

    这个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);
    

    【讨论】:

      【解决方案2】:

      问题 1.string 定义为 char 对您不起作用。你需要一个数组。

      定义char string[100] = {0};

      问题2.scanf("%s",&amp;string);不是必须的,可以作为scanf("%s",string);使用

      问题 3. if(string == 'h'),错了。无法使用 == 运算符比较数组内容。你必须使用strcmp() 函数。

      【讨论】:

      • @DanielKleinstein 谢谢。我只是不再看第一个不正确的实例。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-08-09
      • 1970-01-01
      • 1970-01-01
      • 2014-04-15
      • 1970-01-01
      • 2011-10-18
      • 1970-01-01
      相关资源
      最近更新 更多