简体   繁体   English

uint8 with scanf和printf in C

[英]uint8 with scanf and printf in C

This code unite is a part of a bigger code of a database in C. This part takes grades of students. 这个代码联合是C中更大的数据库代码的一部分。这部分需要学生的成绩。 requirements are to use typedef unsigned char uint8 instead of a simple int . 要求是使用typedef unsigned char uint8而不是简单的int For the life of me I can't make it work. 对于我的生活,我无法使它成功。 When I use %c in scanf it skips. 当我在scanf中使用%c时,它会跳过。 In print if it prints the first digit sometimes. 在打印时,如果它有时打印第一个数字。 So this is the code with int and it's working fine, how do I make it work with uint8 or unsigned char??? 所以这是带有int的代码并且工作正常,如何使用uint8或unsigned char?

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <ctype.h>
#include <inttypes.h>
#include <string.h>
//typedef unsigned char uint8;
typedef unsigned int uint8;
int main(void)
{
    uint8 grades_t[3], gr_c, g_temp;
    for (gr_c = 0; gr_c < 3;)
        {
            printf("please enter the grade (0-100) of subject no%d: ", gr_c+1);
            scanf("%d", &g_temp);
            if (g_temp < 0 || g_temp > 100) //only accept values between 0-100
                {
                    printf("please enter valid grade from 0 - 100!\n");
                    gr_c --; //if value is out of range, decrement  
                }

            else //store value 
                {
                    grades_t[gr_c] = g_temp; 

                }
            gr_c++;
        }
        printf("grade = %d\n", grades_t[0]); //unite test
        printf("grade = %d\n", grades_t[1]);
        printf("grade = %d", grades_t[2]);
    return 0;
}

You want to treat the unsigned char as a small integer, not as a character. 您希望将unsigned char视为小整数,而不是字符。 Assuming C99 or later, you'll use: 假设C99或更高版本,您将使用:

unsigned char u1;  // Or, given typedef unsigned char uint8; uint8 u1;

if (scanf("%hhu", &u1) != 1)
    …oops…

printf("Value: %d\n", u1);

The hh in the scanf() conversion specifies that the pointer provided is to a (unsigned) char . scanf()转换中的hh指定提供的指针是(unsigned) char There's no need for the corresponding change in the printf() because u1 will be promoted to int automatically. printf()不需要相应的更改,因为u1将自动提升为int However, if you wish, you can use: 但是,如果您愿意,可以使用:

printf("Value: %hhu\n", u1);

This preserves the symmetry in printf() and scanf() . 这保留了printf()scanf()的对称性。 I observe that the macros in <inttypes.h> aren't directly applicable. 我发现<inttypes.h>中的宏不能直接应用。 The macros such as SCNu8 and PRIu8 apply to uint8_t , not to uint8 . 诸如SCNu8PRIu8类的宏适用于uint8_t ,而不适用于uint8 That said, they could probably be used and they'd probably work OK — assuming they are provided in <inttypes.h> at all: 也就是说,它们可能会被使用,它们可能正常工作 - 假设它们在<inttypes.h>中提供:

if (scanf("%" SCNu8, &u1) != 1)
    …oops…

printf("Value: %" PRIu8 "\n", u1);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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