【发布时间】:2018-09-19 19:57:29
【问题描述】:
我试图从一个函数中获取 userInput 而不是在另一个函数中使用它。当我在第一次输入字符时测试 char 是否在 DetermineWhatCommand 函数中工作时,我得到了错误的输出,但之后下一个输入的字符串会正确显示。
#include<stdio.h>
#include<string.h>
#define MAX 100
char * GetUserInput(){
char userInput[MAX];
fgets(userInput, sizeof (userInput), stdin);
userInput[strcspn(userInput, "\n")] = '\0';
return userInput;
}
void DetermineWhatCommand(char *userInput){
printf(userInput);
}
int main() {
char * userInput;
userInput = new char[MAX];
char exitTest[] = "exit";
while(strcmp(exitTest, userInput) != 0){
userInput = GetUserInput();
DetermineWhatCommand(userInput);
}
return 0;
}
输出:
Hello //First string entered
@ //What the output in the function looks like
Hello //Second string entered
Hello //What the output in the function looks like
【问题讨论】:
-
在
C中使用new而不是C++? -
是的,谢谢你的提醒,好几年没用过C了。
-
很想将它作为How to access a local variable from a different function using pointers? 的副本关闭,它甚至被标记为 C++(以及 C)。