fgets()和sscanf()仅将第一个整数存储在数组中

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

我试图使用Enter键终止Integer数组输入。因此,我想到了使用fgets和sscanf(),但是每次我仅获得第一个价值时,我都尝试了几种方法。有人可以帮我做错什么。

#include<stdio.h>
int main(){
int inp[100]={0};

int c=0,n;
char str[100]={0};
char *data = str;

while ((NULL != fgets(str, sizeof str, stdin)) && (str[0] != '\n')) {
    if (1 != sscanf(str,"%d",&inp[c])) {
        puts("Input was not an integer, try again.\n");
        continue;
    }
    printf("\ninp[%d] = %d",c,inp[c]);
    c++;
    if (c >= 100) break;
}
}

我添加了代码和输出的快照-CodeOutput

c scanf fgets
1个回答
0
投票
int main()
{
int inp[100]={0};

int c=0,n= 0;
char str[100]={0};
char *data = str;

while ((NULL != fgets(str, sizeof str, stdin)) && (str[0] != '\n')) {
    data = str;
    n = 0;
    while (1 == sscanf(data,"%d%n",&inp[c], &n)) {
    printf("\ninp[%d] = %d\n",c,inp[c]);
    data +=n;
    c++;
    if (c >= 100) break;
    }   
}
}
© www.soinside.com 2019 - 2024. All rights reserved.