[英]Return value of fgets into main function
Function fWord
询问我的输入,并且应该返回它遇到的第一个单词(直到第一个空格)。 它适用于 Online Visual Studio,但如果我尝试使用 codeBlocks 编译它,我的输入不会被打印。
#include <stdio.h>
#include <string.h>
#include <ctype.h>
char * fWord();
char * test;
int main()
{
test = fWord();
printf("%s\n", test);
return 0;
}
char * fWord() // ONLY READ THE FIRST WORD
{
char buffer[20];
char * input = buffer;
fgets(input, sizeof(input), stdin);
input = strtok(input, " ");
input[strcspn(input, "\r\n")] = 0; // REMOVES NEWLINE FROM GETLINE
return input;
}
缓冲区
char buffer[20];
有本地存储。 它在堆栈中分配,并在fWord
返回后立即释放。
您需要在外部分配它(作为全局变量或作为 function main
的局部变量将其作为fWord
的新参数传递)或在fWord
内动态分配(使用malloc ()
)。
此外,正如@lurker 在评论部分正确注意到的那样,调用
fgets(input, sizeof(input), stdin);
告诉fgets()
最多读取sizeof(input)
字符。 但它实际上是char *
指针的大小,根据您的架构,可以是 4 或 8。
总之,您的程序将变为:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define MAX_INPUT_LEN 20
char * fWord(void);
int main(void)
{
char *test = fWord();
if (test) //fWord might return a NULL pointer
{
printf("%s\n", test);
free(test);
}
return 0;
}
char * fWord(void) // ONLY READ THE FIRST WORD
{
char * input = malloc(MAX_INPUT_LEN);
if (input)
{
fgets(input, MAX_INPUT_LEN, stdin);
input[strcspn(input, "\r\n")] = 0; // REMOVES NEWLINE FROM GETLINE
input = strtok(input, " ");
}
return input;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.