BoHyunK
BoHyunK

Reputation: 69

Why are the trash values printed?

My code is...

#include <stdio.h>
int main(){
    char name[20];
    int age;
    char department;
    double key;
    int i=0;
    while( (scanf("%c", &name[i])) == 1 ){
        i++;
    }
    name[i] = '\0';

    scanf("%d", &age);
    scanf("%c",&department);
    scanf("%lf",&key);


    puts(name);
    printf ("%d\n",age);
    printf("%c\n",department);
    printf("%g",key);

    return 0;
}

and input value is

mark
20
A
3.154

The result output should be same as input

mark
20
A
3.154

but what i got is ...

mark
20
A
3.154

32766
�

I wonder where

32766
�

comes from...

Upvotes: 0

Views: 49

Answers (2)

paxdiablo
paxdiablo

Reputation: 881093

The code

while( (scanf("%c", &name[i])) == 1 ){
    i++;
}

will read all characters that it can, it will not stop at the end of mark.

Hence, the entire four lines are being read by that loop into name, then the scan calls following that are failing because there's no more input, meaning that the age, department and key values are left at whatever arbitrary value they had when they were created.

In other words, your output can be explained thusly:

mark  \
20     \
A       >-- name
3.154  /
      /
32766    -- age (and probably nul for department)
�       -- key

If you want to do line-based input, this answer provides a handy function for doing so, with buffer overflow protection and so on. For the strings, you just use them as entered, while the non-strings can be converted using sscanf on the buffer.

Upvotes: 2

Jonathan Leffler
Jonathan Leffler

Reputation: 753455

Your first loop with while (scanf("%c", &name[i]) == 1) should read all of standard input, quite probably overflowing the name array. The scanf() calls afterwards should fail — you should be checking the return value from each of those. That you get the input reprinted is because you first print name; the rest then is from the uninitialized (or overwritten) variables. It might be easier to see if you used printf("[[%s]]\n", name); instead of puts(name); — you'd see the square brackets around all your input.

You could fix it by adding:

if (name[i] == '\n')
    break;

inside that initial while loop.

Upvotes: 1

Related Questions