如何使用 fgets() 而不导致错误并包含“.”在输出的同一行?

问题描述 投票:0回答:1

我正在学习和练习'C'。使用 fgets() 函数对我来说是一个挑战。例如,下面的代码运行得非常好。当我运行这段代码时,它使用我妈妈的名字(名字姓氏)作为输入,但“。”被放置在下一行。如何在输出的同一行获得周期?

#include <stdio.h>

int main() 
{
    char motherName[30];
    printf("Enter your mother's full name: ");
    fgets(motherName, sizeof(motherName), stdin);
    printf("Your mom's full name is %s.", motherName);
    
    return 0;
}

还有另一个疑问。当将 fgets() 函数与其他变量输入一起使用时,会导致错误。前两个输入被正确接收,输出正是我想要的方式。但是当涉及到 fgets() 时,它不接受任何输入。我希望你能帮我解决这个问题。我也是堆栈溢出的新手,感谢您的帮助!

#include <stdio.h>

int main()
{
    int num;
    printf("What's your favorite number: ");
    scanf("%d", &num);
    printf("Your favorite number is %d.\n", num);

    char name[20];
    printf("Enter your name: ");
    scanf("%s", name);
    printf("Your name is %s.\n", name);

    char motherName[30];
    printf("Enter your mother's full name: ");
    fgets(motherName, sizeof(motherName), stdin);
    printf("%s is your mom's full name.", motherName);

    return 0;
}
c input scanf fgets
1个回答
0
投票

要处理

fgets()
之后的换行符(换行):

#include <string.h> // add this header file
/* ... */
    fgets(motherName, sizeof(motherName), stdin);
    motherName[ strcspn(motherName, '\n') ] = '\0'; // add this line to obliterate LF

第二个问题,

scanf()
fgets()
同时使用,就是一场摔跤比赛。前者会在缓冲区中留下(意外的)空白(包括 LF)。而且,正如您所做的那样,大多数代码不会检查
scanf()
是否分配了所有预期的值。

既然您正在使用

fgets()
,请停止使用
scanf()
进行输入。标准库包含将字符串分隔为 tokens (
strtok()
) 并将这些标记转换为
int
(
strtol()
) 或
double
(
strtod()
) 所需的所有函数。这就是大男孩的做法。


离开键盘,去了解标准库提供的函数。

© www.soinside.com 2019 - 2024. All rights reserved.