gpt4 book ai didi

c - fgets、sscanf 和写入数组

转载 作者:太空宇宙 更新时间:2023-11-04 02:53:21 24 4
gpt4 key购买 nike

这里是初学者问题,我没能找到相关的例子。我正在开发一个 C 程序,该程序将使用 fgets 和 sscanf 从 stdin 获取整数输入,然后将其写入数组。但是,我不确定如何让 fgets 写入数组。

#define MAXINT 512
char input[MAXINT]

int main(void)
{
int i;
int j;
int count=0;
int retval;

while (1==1) {
fgets(input, MAXINT[count], stdin);
retval = sscanf(input, "%d", &i);

if (retval == 1) {
count = count++;
}
else
if (retval != 1) {
break;
}
}

我会简单地将 fgets 放在 for 循环中吗?还是比这更复杂?

最佳答案

fgets() 读入字符串(char 数组),而不是 int 数组。

你的循环应该是:

char line[4096];

while (fgets(line, sizeof(line), stdin) != 0)
{
...code using sscanf() iteratively to read into the array of int...
}

不检查输入会导致问题。充其量,您的代码很可能会处理最后一行输入两次。只有当这意味着我的退款被处理了两次时,你才可以这样做。在最坏的情况下,您的代码可能永远不会终止,直到您的程序无聊至死,或内存不足,或者您对它失去耐心并杀死它。

[This] doesn't answer the question of how I would write to the array within the while loop. Would I enclose the sscanf function in a for loop for however many numbers got entered? Would I set something up to run each time Enter is pressed?

假设每行只有一个数字,那么循环体中的代码很简单:

char line[4096];
int array[1024];
int i = 0;

while (fgets(line, sizeof(line), stdin) != 0)
{
if (i >= 1024)
break; // ...too many numbers for array...
if (sscanf(line, "%d", &array[i++]) != 1)
...report error and return/exit...
}

注意如果同一行有乱码(其他数字,非数字),这段代码不会注意到;它只是获取第一个数字(如果有的话)并忽略其余数字。

如果每行需要多个数字,请查看 How to use sscanf() in loops获取更多信息。

如果您想要一个空行来终止输入,那么使用fscanf()scanf() 不是一个选项;他们通读多个空白行以寻找输入。

关于c - fgets、sscanf 和写入数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19846016/

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