Reputation: 850
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!
Upvotes: 1
Views: 376
Reputation: 24857
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.
Upvotes: 3