简体   繁体   中英

Using fscanf to read a string and then a variable number of integers to EOF

I'm having a little trouble starting a project I have been assigned. I can't use string operators, fgets , etc. I need to scan a file to EOF.

Here is an example of the file:

AND 3 2 1
OR 4 5 6
SPECIAL 4 5 6 7

What I tried to do is set up a while loop:

while (fscanf(circuit, "%s", cur_gate) != EOF){

then tried to check what the cur_gate string is:

if (cur_gate[0] == 'A'){

The problem is, I don't know how I would scan 3 integers after reading the string. Then eventually, once it reads SPECIAL, I need to scan 4 integers.

I want to store the first integer in a array called Output, and the rest in an array called INPUT.

So to summarize, how would I fscanf a string and then fscanf a variable amount of integers depending on the string I have read?

Based on what I understood from your question, below code would help you.

I assumed, that you just wanted to store all the outputs in just one array, and similarly all the inputs in one array. So, as per your example you want to store 3,4,4 (first integer just after word) in output array. Rest of the integers need to go to another input array.

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

#define MAX_CHAR  256
#define MAX_IN    100
#define MAX_OUT   100

enum
{
    FALSE = 0,
    TRUE
};

int main()
{
    char word[MAX_CHAR];
    FILE *fp;

    int i = 0, in[MAX_IN];
    int o = 0, out[MAX_OUT];

    int flag = FALSE;

    fp = fopen("dict.txt","r");
    if(NULL != fp)
    {
        while(fscanf(fp, "%s", word) != EOF)
        {
            printf("%s\n",word);
            if(0 != isalpha(word[0]))
            {
                flag = TRUE;
            }
            else
            {
                if(TRUE == flag)
                {
                    out[o] = atoi(word);
                    o++;
                    flag = FALSE;
                }
                else
                {
                    in[i] = atoi(word);
                    i++;
                }
            }
        }
        fclose(fp);
    }
    int j;
    printf("INPUT: ");
    for(j=0; j<i; j++)
    {
        printf("%d\t",in[j]);
    }
    printf("\n");
    printf("OUTPUT: ");
    for(j=0; j<o; j++)
    {
        printf("%d\t",out[j]);
    }
    printf("\n");
    return(0);
}

OUTPUT for the example of file you have given

INPUT: 2        1       5       6       5       6       7
OUTPUT: 3       4       4

DISCLAIMER: The code has been compiled and tested in my environment. I encourage you to take care of error handling scenarios yourself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM