我试图询问用户他们想在我制作的“外壳”中做什么。我的代码如下:
/* 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);
}
最佳答案
- 初始化响应,例如响应[0] = 0。
- 退出长度为 5(结尾为零)。使用 char exit[] = "退出";否则你的 strncmp 可能会失败。
- 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/