简体   繁体   中英

Why is the output of my C program incorrect?

This is my code in C that reads data from input:

#include<string.h>
#define MAX 3
char a[MAX];
char b[MAX];
void ReadFirstNumber();
void ReadSecondNumber();
int lb,la=0;
void main()
{
    ReadFirstNumber();
    ReadSecondNumber();
    printf("\n First Number > %d %d %d \n",a[0],a[1],a[2]);
    printf(" Second Number >  %d %d %d \n",b[0],b[1],b[2]);
}
void ReadFirstNumber()
{
    int i=0;
    printf("Enter the first number:");
    scanf("%s", a);
    la=strlen(a)-1;
    for(i=0;i<=la;i++)
    {
        a[i] = a[i] -48;
    }
}
void ReadSecondNumber()
{
    int j=0;
    printf("Enter the Second number:");
    scanf("%s", b);
    lb=strlen(b)-1;
    for(j=0;j<=lb;j++)
    {
        b[j] = b[j] -48;
    }
}

input first number example: 123
input second number example: 456 or any 3-digit number

//output
First Number    **0**23
Second Number   456 

The output for first number is 023

The first character is Zero ! but the output for second number is ok.

When I comment out second function //ReadSecondNumber(); it worked perfectly!

You failed to allow enough space for the null terminator char that scanf("%s",...) writes at the end of 'strings'. Increase the value of the MAX #define. You may as well put in something sanely larger, eg 32.

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