Reputation: 81
I'm trying to print out comma seperated values in my C program, but I think I keep getting memory allocations instead. When running from the command line, this happens.
1
49 this is the response
10 this is the response
1
49 this is the response
10 this is the response
Here is my program:
void main(){
int j;
int idnum;
j = 0;
char entry[99];
do{
idnum = get_field(entry);
j++;
}
while(idnum!='\n' && idnum!= ',' && j!= MAXTYPES);
int recur = 0;
while (recur != 4){
printf("%4d\n", entry[recur]);
recur++;
}
printf("\nEnd of Input\n");
}
int get_field(char entry[]){
int idnum;
char n;
int j = 0;
char temp[45];
while ((n=getchar())!= EOF){
printf("%d this is the response\n",n);
}
return idnum;
}
Upvotes: 1
Views: 61
Reputation: 206747
Problems I see:
In get_field
, you have not initialized idnum
and returning it from the function.
In get_field
, the while
loop to read the data is strange. I am not sure what you are trying to accomplish. However, you if type 1
and then press Enter
, two characters are added to the input stream: '1'
and '\n'
. You are reading them as char, using getchar
, and printing them as int
(by using the "%d"
format).
That explains the output you are getting.
49 is the decimal representation of '1'
.
10 is the decimal representation of '\n'
The return type of getchar
is int
. You should change the type of n
in get_field
to int
from char
. That could be source of problems depending on the platform you are working in.
Upvotes: 1
Reputation: 559
Since n
is a char
type data.So,you've to use %c
instead of %d
Like this:
printf("%c this is the response\n",n);
Upvotes: 0
Reputation: 53386
With %d
you are printing the ASCII values. ASCII value of 1 is 49 and of \n
is 10.
These are what you are getting.
You may want to print them with %c
.
Upvotes: 0