gpt4 book ai didi

c - 如何将 int 和 double 作为输入而不是 char?

转载 作者:太空宇宙 更新时间:2023-11-04 06:20:25 25 4
gpt4 key购买 nike

我正在尝试创建一个 while 循环,用于将 intdouble 作为输入。但有时我想跳过输入中的 char,然后继续循环。

这将跳过循环,我仍想使用 scanf:

scanf("%d%lf", &num,&n_double);
while((num != 'a')&&(n_double != 'a'))

最佳答案

首先读取整行,然后使用sscanf将输入行解析为整数和 double 。但是,如果解析未能给出 int 和 double,则将其作为错误情况得出结论,即该行中存在一个 char。

你可以试试这段代码:

int main(int argc, char const *argv[])
{
char line[100];
while(fgets(line, 100, stdin)) {
int i;
double d;
if(sscanf(line, "%d %lf", &i, &d) == 2) {
printf("%d %lf\n", i, d);
}
else {
printf("wrong input!\n");
}
}
return 0;
}

根据评论编辑:

来自 cppreference.com

char *fgets( char *str, int count, FILE *stream );

Parameters

str - pointer to an element of a char array

count - maximum number of characters to write (typically the length of str)

stream - file stream to read the data from

Return value

str on success, null pointer on failure.

所以,while(fgets(str...)) 翻译成“while fgets doesn't return null”,翻译成“while fgets continues to successfully”读取输入流(在本例中是 stdin,标准输入)”。

请查看文档以获得进一步的说明。

关于c - 如何将 int 和 double 作为输入而不是 char?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36224292/

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