我的代码是:
#include <stdio.h>
#include <string.h>
char *getUserInput() {
char command[65];
//Ask the user for valid input
printf("Please enter a command:\n");
fgets(command, 65, stdin);
//Remove newline
command[strcspn(command, "\n")] = 0;
return command;
}
int main() {
char *recCommand = getUserInput();
printf("%s", recCommand);
return 0;
}
执行此代码时,这是控制台:
Please enter a command:
Test <-- this is the command I entered
*weird unknown characters returned to console*
为什么有奇怪的未知字符被返回到控制台而不是“测试”?
答案 0 :(得分:3)
这是因为您要返回局部变量的值。试着把它放在:
char *getUserInput() {
static char command[65];
//Ask the user for valid input
printf("Please enter a command:\n");
fgets(command, 65, stdin);
//Remove newline
command[strcspn(command, "\n")] = 0;
return command;
}
答案 1 :(得分:3)
在做了一些更多的研究之后,似乎最好的方法是从main函数传入一个char数组,用于存储来自getUserInput的输入。
这是我修改后的代码:
void getUserInput(char *command) {
//Ask the user for valid input
printf("Please enter a command:\n");
fgets(command, 65, stdin);
//Remove newline/return carriage
command[strcspn(command, "\n")] = 0;
}
int main {
char recCommand[65];
getUserInput(recCommand);
printf("%s", recCommand);
return 0;
}