I am trying to write a program that reads characters (until end is reached) on N lines and stores the characters as decimal numbers in an array and then prints the array. Input of characters is just 0-9 or A-Z.
Here is my code:
#include <stdio.h>
#define SIZE 1000
int main()
{
int c, N;
int i,j,k, n;
int x[SIZE];
scanf("%d\n", &N);
for(i = 0; i < N; i++){
c = getchar();
for(j = 0; c!=EOF; j++)
{
if(c<='9') x[j] = c - 48;
else x[j] = c - 'A' + 10;
n++;
c = getchar();
}
for(k=0;k<n;k++) printf("%d ", x[k]);
}
return 0;
}
an example input:
2
ABC
ABD
The desire output:
10 11 12
10 11 13
But my code outputs:
10 11 12 -38 10 11 13
10 11 12 -38 10 11 13
I tried to write c!='\n' but it gives runtime error
UPDATE: I FIXED it it works now, I had to set n to 0 again.
#include <stdio.h>
#define SIZE 1000
int main()
{
int c, N;
int i,j,k, n=0;
int x[SIZE];
scanf("%d\n", &N);
for(i = 0; i < N; i++){
n = 0;
for(j = 0; (c = getchar()) != '\n'; j++)
{
if(c ==EOF) break;
if(c<='9') x[j] = c - 48;
else x[j] = c - 'A' + 10;
n++;
}
for(k=0;k<n;k++) {printf("%d ", x[k]); } printf("\n");
}
return 0;
}