簡體   English   中英

fgets 的返回值進入主 function

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM