简体   繁体   中英

Unexpected behaviour while taking input in C language

I am trying to run this code which seems fine to me but the end results are not much convincing. Here's the code:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
    unsigned char nT,nF;    
    char extension[5];

    puts("Enter No. of Testcases & Faults");
    scanf("%d %d %s", &nT, &nF, extension);
    printf("%d %d\n",nT,nF);
    getch();
}

Below is the sample input:

Enter No. of Testcases & Faults
50 50 code

Below is the output:

0 50

Below is the Expected output:

50 50

Note: I am bounded to use unsigned char and cannot use unsigned int.

I am using DevCpp 4.9.9.2. Please help if anyone has got the solution or the reason for why this is happening.

Look into your scanf clause. You are passing two (pointers to) unsigned char variables to it, yet declare that you are reading two ints in your format specifier ( %d specifier). Pass %hhu if you want to read unsigned char .

When you pass &extension to scanf there is no need to use ampersand. The name of the array gets converted to the pointer to its first element, so it's sufficient to pass just extension .

You are also using a very old IDE (Dev-C++), that is no longer developed. Probably the underlying compiler is dated as well. I advise to use newer tools, Code::Blocks is actively developed, quite newbie-friendly and similar to Dev-C++ to a certain extent.

However, on Windows platforms, the MSVCRT library does not support the %hhu format specifier, as has been noted in this question . MingGW compiler relies on this implementation, so it does not support %hhu on windows as well. Cygwin is a project that simulates Linux environment on Windows and is distributed with its own version of C library, that supports, among other things, %hhu . As a sidenote, you can configure Code::Blocks to work with Cygwin (as described here ). I don't know if the same can be achieved with Dev-C++.

    #include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
    unsigned int nT,nF;    
    char extension[5];

    puts("Enter No. of Testcases & Faults");
    scanf("%d %d %s", &nT, &nF, extension);
    printf("%d %d\n",nT,nF);
    getch();
}
    #include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
    unsigned char nT,nF;    
    char extension[5];

    puts("Enter No. of Testcases & Faults");
    scanf("%hhu %hhu %s", &nT, &nF, extension);
    printf("%hhu %hhu\n",nT,nF);
   // getch();
}

You can see output on below image

在此输入图像描述

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