c - 如何将输入响应传递给 C 中的函数

标签 c arrays pointers

我试图询问用户他们想在我制作的“外壳”中做什么。我的代码如下:

    /* Create a char array to hold response */
char response[80];
char exit[4] = "Exit";

printf("\n\n     Commands are as followed:");
printf("\n------------------------------------");
printf("\n'cd' 'Directory' (Changes Directorys)");
printf("\n'cp' 'FileName'  (Copys File)");
printf("\n'Exit'           (Exits the program)");
printf("\n'ls'             (Displays Info)");
printf("\n------------------------------------\n\n");

while(strcmp(exit, response) != 0){

/* Ask user for input */
fputs("$> ", stdout);

/* Flush */
fflush(stdout);

/* Make sure response is not NULL */
if ( fgets(response, sizeof response, stdin) != NULL )
{
    /* search for newline character */
    char *newline = strchr(response, '\n'); 
    if ( newline != NULL )
    {
        /* overwrite trailing newline */
        *newline = '\0'; 
    }

    actOnResponse(fs, response); 
 }

现在我的问题涉及 actOnResponse() 函数。我想将响应传递给函数。在函数中,我将解析响应和字符串,将其与值“cd”、“cp”和“ls”进行比较。但是我如何传递它呢?现在,当我运行该程序时,它会给我一个段错误(核心转储)。

任何人都可以指出我做错了什么!谢谢。

这是 actOnResponse() 函数:

void actOnResponse(int fs, char *response){

printf("%s" , response);
}

最佳答案

  1. 初始化响应,例如响应[0] = 0。
  2. 退出长度为 5(结尾为零)。使用 char exit[] = "退出";否则你的 strncmp 可能会失败。
  3. fs 未定义。

此代码有效:

#include <stdio.h>
#include <string.h>

void actOnResponse(int fs, char *response){
  printf("%s\n" , response);
}

void main() {
  /* Create a char array to hold response */
  char response[80];
  char exit[] = "Exit";
  int fs = 0;

  response[0] = 0;

  printf("\n\n     Commands are as followed:");
  printf("\n------------------------------------");
  printf("\n'cd' 'Directory' (Changes Directorys)");
  printf("\n'cp' 'FileName'  (Copys File)");
  printf("\n'Exit'           (Exits the program)");
  printf("\n'ls'             (Displays Info)");
  printf("\n------------------------------------\n\n");

  while (strcmp(exit, response) != 0) {
    /* Ask user for input */
    fputs("$> ", stdout);

    /* Flush */
    fflush(stdout);

    /* Make sure response is not NULL */
    if (fgets(response, sizeof response, stdin) != NULL) {
      /* search for newline character */
      char *newline = strchr(response, '\n');
      if (newline != NULL) {
        /* overwrite trailing newline */
        *newline = '\0';
      }
      actOnResponse(fs, response);
    }
  }
}

(保存为 test.c。运行 gcc -o test test.o 然后 ./test)。

关于c - 如何将输入响应传递给 C 中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23500228/

相关文章:

c++ - 二叉树递归插入错误

c - 什么是一组整数集的简单 C 库?

python - 我如何使用Numpy设置具有2d索引数组的4d数组

php - 如何在 PHP Laravel 中对子数组项进行分组和求和

c++ - 制作一个充满基础 Complex 类的二维数组

通过将指针传递给 c 中的函数来创建二维数组

swift - 解析 - 查询 'includeKey' 未在正确的子类中获取对象

c++ - C/C++ 优化 : negate doubles fast

c++ - Arduino 中不需要的符号扩展

c++ - 如何检测未使用的宏定义和类型定义?