将fgets的值返回到主函数 [英] Return value of fgets into main function
问题描述
函数 fWord
询问我的输入,并应返回遇到的第一个单词(直到第一个空格).它可以在Online Visual Studio上运行,但是如果我尝试使用codeBlocks进行编译,则不会打印我的输入.
Function fWord
asks my input, and should return the first word it encounters (until the first space).
It works on Online Visual Studio, but if I try to compile it with codeBlocks, my input doesn't get printed.
#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
返回时立即释放.
has local storage. It is allocated in the stack and it is released as soon as fWord
returns.
您需要在外部进行分配(作为全局变量或作为函数 main
的局部变量,将其作为 fWord
的新参数传递)或保持在 fWord
,但动态(使用 malloc()
).
You need to allocate it externally (either as global variable or as a local variable of function main
passing it as a new parameter of fWord
) or keep allocating within fWord
but dynamically (using malloc ()
).
此外,@ lurker在评论部分正确地注意到了呼叫
Furthermore, as correctly noticed by @lurker in comments section, the call
fgets(input, sizeof(input), stdin);
告诉 fgets()
最多读取 sizeof(input)
个字符.但这实际上是 char *
指针的大小,根据您的体系结构为4或8.
tells fgets()
to read at most sizeof(input)
characters. But it will actually be the size of a char *
pointer, either 4 or 8 according to your architecture.
最后,您的程序将变为:
In conclusion, your program will become:
#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;
}
这篇关于将fgets的值返回到主函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!