简体   繁体   中英

C: integers not printing correctly

(Hi guys. I tried searching for the problem I'm having and can't seem to find the solution so far. I'm totally new to programming and am learning C currently, but I am a complete noob so I apologize in advance if I'm making a dumb mistake.)

Here's the problem: Im tryna scan 4 integers and print their values using a while loop. The problem is, the numbers are being printed as crazy long numbers not as the ints that are input. I tried scanning and printing a single int and it printed fine but once I use multiple ints, it starts screwing aroud.

Here's my code:

#include <stdio.h>

int main()
{
    int i, n1,n2,n3,n4;
    printf("Enter 4 numbers.");
    for(i=0;i<4;i++)
    {
        printf("\n\nEnter number %d: ", i+1);
        scanf("%d,%d,%d,%d", &n1,&n2,&n3,&n4);
        printf("%d,%d,%d,%d", n1,n2,n3,n4);
    }

}

Two things:

  1. the input format given in scanf() should match exactly to the input value for a successful scan . [You need to have , s in your input]
  2. Always check for the success of scanf() to ensure proper scanning of value. scanf() returns the number of items successfully matched and scanned.

So, you should change your code to something like,

 if ( scanf("%d,%d,%d,%d", &n1,&n2,&n3,&n4) == 4)
 {
       // use n1, n2, n3, n4
 }
 else
   //don't use them, return some error.

Note: Always initialize local variables. Many a time it will save you from the undefined behaviour of read-before-write scenario.

Also, [maybe?] the for loop is not required, as you're scanning all the four numbers at a time.

When you have scanf("%d,%d,%d,%d", &n1,&n2,&n3,&n4);

you must give your input as say 1,2,3,4 ( commas are needed)

And you said you want to read 4 numbers and you have a scanf that gets the 4 numbers. So there is no need for a loop here. If you want to loop get one number each time inside the loop.

You are looping 4 times, expecting to read 4 numbers in each loop...

Generally speaking, scanf() is a poor tool for parsing any kind of input that might not match the expected format -- and nothing is as fickle as user input. I usually advise reading in whole lines of input (via fgets() ), and then parsing them in-memory as appropriate (which, in this case, would probably mean using strtol() and checking how much of the input string was parsed via its second parameter).

This, for example, is much more robust:

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

#define LINELEN_MAX 100

int main()
{
    int i;
    char input[ LINELEN_MAX ];
    char * current;
    char * end;

    while ( 1 )
    {
        // whitespaces or commas do not matter,
        // and neither does the amount of numbers.
        puts( "Enter numbers, or 'q' to quit." );

        if ( fgets( input, LINELEN_MAX, stdin ) == NULL )
        {
            puts( "Error on read." );
            return EXIT_FAILURE;
        }
        if ( *input == 'q' )
        {
            puts( "Quitting." );
            return EXIT_SUCCESS;
        }
        if ( input[ strlen( input ) - 1 ] != '\n' )
        {
            puts( "Line exceeded maximum width." );
            return EXIT_FAILURE;
        }

        current = input;
        end = input;

        while ( *current )
        {
            if ( !isdigit( *current ) )
            {
                // skip non-digits
                ++current;
            }
            else
            {
                // parse 1..n digits and print
                printf( "%ld\n", strtol( current, &end, 10 ) );
                current = end;
            }
        }
    }
}

One reason may be that all your values are being printed onto the same line without any space between them.

Basically you are printing 4 numbers continuously in one line which makes it look like one big number.

I advise you to add a new line format specifier.(If you are a newbie, then you might not understand this, so here are some links that may be useful)

http://www.codingunit.com/printf-format-specifiers-format-conversions-and-formatted-output

There is also the problem that you are reading 4 numbers 4 times , that is you are reading 16 variables in total. For this code , you actually don't need a for loop.

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