0

My simple program is read from the text file one word at a time.

example text file. (below)

N 101001 Circular Queue 11 1

N 123456 List Linker 11 5

N 666666 Pseudocode Gen 38 3

N 110010 Stack Stretcher 3 2

and simple codes including variables etc...

char function;
    int number, init_stock, reorder;
    char info[100];

    FILE *fp;
    if((fp = fopen("input.txt", "r")) == NULL)
    {
        printf("input open failed\n");
        return 0;
    }
    while(!feof(fp))
    {
        fscanf(fp, "%c %d %[A-z, ] %d %d ", &function, &number, info, &init_stock, &reorder);

    }

When a variable was changed within the ' while loop',

I expected to affect it the next loop as well.

so.. first, 'Circular Queue' was stored in 'info'.

Second, when 'List Linker' was stored in 'info' because second string is shorter than first string,

I thought that the info array had string like this 'List Linkerue'.

  1. info -- Circular Queue
  2. info -- List Linker+ue

But the info seemed to be reset every time, and I do not know why.

melpomene
  • 84,125
  • 8
  • 85
  • 148
Sangeui
  • 11
  • 1
  • 4

1 Answers1

0

On the first pass the content of info is "Circular Queue \0" The \0 at the end represents a single zero byte, it is the null character. This tells functions like printf where string ends.

Note that there is also a blank space at the end.

On the second pass the content of info is "List Linker \0e". As you suspected, fscanf didn't fill the whole string. But it did add the null character, so you can't see the e at the end. Content of info will be

1st pass: "Circular Queue " ... followed by random bytes
2nd pass: "List Linker \0e "

You can also improve your function by changing the format to %99[A-z, ] because info is 100 bytes (including the null character) And make sure fscanf reads 5 values as expected. You might also consider changing the input so the values are separated by commas.

while(fscanf(fp, "%c %d %99[A-z, ] %d %d ", 
    &function, &number, info, &init_stock, &reorder) == 5)
{
    //optional: remove the extra space at the end of info
    int len = strlen(info);
    if(len)
        if(info[len - 1] == ' ')
            info[len - 1] = 0;
    printf("string: [%s] %d\n", info, number);
}
Barmak Shemirani
  • 30,904
  • 6
  • 40
  • 77