简体   繁体   中英

variable is losing its value in c program

This is written in 'c' and compiled with gcc. I'm not sure what else you need to know.

The smallest complete example I could put together is shown here. The variable 'numatoms' loses its value when it gets to line 23 (after the scanf()).

I'm stumped. Maybe it has something to do with scanf() overwritting the space for numatoms?

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

/*
 * 
 */
int main(int argc, char** argv) {
uint8_t numatoms;
uint8_t r;
char a[20];

do {
    printf("NO. OF ATOMS?");
    fflush(stdout);
    scanf("%d", &numatoms);
    printf("\r\n");
    for(;;){
        printf("value of numatoms is %u\r\n", numatoms);
        printf("RAY?");
        fflush(stdout);
        scanf("%u", &r);
        printf("value of numatoms is %u\r\n", numatoms);
        if(r < 1)
            break;
        else {
            printf("value of numatoms is %u\r\n", numatoms);
        }
    }
    printf("CARE TO TRY AGAIN?");
    fflush(stdout);
    scanf("%s", a); 
    printf("\r\n");           
} while (a[0] == 'y' || a[0] == 'Y');

return (EXIT_SUCCESS);

}

uint8_t is 8 bits long %u reads an unsigned int (probably 32 bits long).

You either need to make numatoms "bigger" (ie unsigned int ) or read the correct size (see scanf can't scan into inttypes (uint8_t) )

You should use macros for format specifiers for integer types defined in the header <inttypes.h> .

From the C Standard (7.8.1 Macros for format specifiers)

1 Each of the following object-like macros expands to a character string literal containing a conversion specifier, possibly modified by a length modifier, suitable for use within the format argument of a formatted input/output function when converting the corresponding integer type. These macro names have the general form of PRI (character string literals for the fprintf and fwprintf family) or SCN (character string literals for the fscanf and fwscanf family),217) followed by the conversion specifier, followed by a name corresponding to a similar type name in 7.20.1. In these names, N represents the width of the type as described in 7.20.1.

The general form of the macro used for unsigned integer types with the conversion specifier u looks like

SCNuN

Here is a demonstrative program

#include <stdio.h>
#include <stdint.h>
#include <inttypes.h>

int main(void) 
{
    uint8_t x;

    scanf( "%" SCNu8, &x );

    printf( "x = %u\n", x );

    return 0;
}

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