如何在c编程中从多行或不同行中获取输入?

时间:2017-09-10 03:53:32

标签: c file

输入中的第一个数字表示后面的行数,而对于每一行,我们想要输出该行中的数字?

输入:

4
1   -2  10000   -50  20  7  445 
9
-98  876  65
223    9876452   212

输出:

7 
1
3
3

3 个答案:

答案 0 :(得分:1)

像这样:

#include <stdio.h>
#include <ctype.h>

int main(void){
    char buff[32];
    fgets(buff, sizeof buff, stdin);//read first line. Is it necessary to check?
    int number_of_lines;
    sscanf(buff, "%d", &number_of_lines);

    while(number_of_lines--){
        int ch;
        int count_numbers = 0;
        while((ch = getchar())!=EOF && ch != '\n'){
            if(isspace(ch))
                continue;//Skip the preceding space
            int i = 0;
            buff[i++] = ch;
            while((ch = getchar()) != EOF && !isspace(ch) && i < sizeof(buff)-1)
                buff[i++] = ch;
            buff[i] = 0;
            ungetc(ch, stdin);//Return one over reading letter
            int num, len;
            if(sscanf(buff, "%d%n", &num, &len)==1 && !buff[len]){
                ++count_numbers;
            }
        }
        printf("%d\n", count_numbers);
        count_numbers = 0;
    }
}

答案 1 :(得分:0)

逐行读取文件。明确检查换行符或EOF。我没有考虑错误处理,但不应该忽略它。

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



int main(){


    int n,i,j;
    char c;

    FILE *fp;
    fp=fopen("example.txt","r");

    fscanf(fp,"%d",&i);

    j=i;

    int *count=(int)calloc(sizeof(int),i);//use calloc to initialize each index to 0;

    while(i){

        while(1){
            fscanf(fp,"%d",&n);


            count[j-i]++;

            c=fgetc(fp);

            if(c=='\n'||c==-1){//check for end of file or newline
                break;
            }


        }

    i--;

    }

    fclose(fp);
    for(i=0;i<j;i++)
       printf("%d\n",count[i]);
    free(count);
    return 0;


}

注意:在文本文件中,每行必须在最后一个数字之后立即以换行符结束,并且两个数字必须用一个空格分隔。以上程序可以针对一般情况进行调整,这只是为了演示!

答案 2 :(得分:-1)

#include<stdio.h>
int main(){
        int t,count,i;
        char s[100];
        scanf("%d\n",&t);
        while(t--){
                gets(s);
                count=1;i=0;
                while(s[i]!='\0'){
                        if(s[i]==' ' && s[i+1]!=' ') count++;
                        i++;
                }
                printf("%d\n",count);
        }
        return 0;
}