gpt4 book ai didi

c - 在 C 中接受空字符串

转载 作者:太空狗 更新时间:2023-10-29 16:33:10 25 4
gpt4 key购买 nike

我的程序可以接受任意长度的数字或空输入。但是,如果输入为空(空格或换行符),程序将继续等待输入。我也试过 fgets 但如果按下空格/换行符,它仍然会在关闭之前等待更多不是空格/换行符的输入。

简化代码:

#include <stdio.h>
main()
{
int num;
scanf("%i",&num);
printf("%i",num);
}

输入:

363792 

输出:

363792

期望:

输入:

输出:

我是 C 的新手,很难完成这个任务。

使用 fgets 的尝试:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
main()
{
int n;
char s[20];

fgets(s,20,stdin);
n = atoi(s);

printf("%i",n);
}

编辑:事实证明我没有正确编译代码。因此,每次我尝试进行更改时,它都只是使用 scanf 查看原始代码。

最佳答案

I also tried fgets but if space/newline is pressed, it still waits for more input that is not a space/newline before closing.

首先 fgets 将在这种情况下起作用。如果您已经向我们展示了您尝试使用 fgets() 究竟做了什么,那么对这个问题的回答将非常狭窄或非常具体。

我尝试使用 fgets() 做同样的事情,下面是代码片段。

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
char string[100];
printf("Enter a number: ");

fgets (string, 100, stdin);
/* Here remove the trailing new line char; not required unless you are trying to print the string */
string[strlen(string) - 1] = '\0';

printf("Num is %d\n", atoi(string));

return 0;
}

如果没有输入或只是输入或空格再输入,则打印的数字将为零并且 fgets() 不会等到您输入有效数字。

另请检查您不应使用 gets 的原因。 Do not use gets()

关于c - 在 C 中接受空字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32609139/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com