Newcomer to C here and struggling a bit.
I'm reading input that looks like this:
9, 344, 100
10, 0, 469
...
I am trying to group each line so that I can send each 3 numbers as parameters in a function.
I have been trying to use scanf but because it maps to memory addresses, I am having a problem with retaining the numbers after each line. I don't know how many lines of data I will have so I cannot make a certain number of arrays. Also, I am limited to functions in <stdio.h>.
If I use scanf is there anyway for me to avoid using malloc?
I have attached an idea below. Looking for suggestions and maybe some clarification on how scanf works.
Apologies if I'm missing something obvious here.
int main() {
int i = 0;
int arr[9]; //9 is just a test number to see if I can get 3 lines of input
char c;
while ((c = getchar()) != EOF) {
scanf("%d", &arr[i]);
scanf("%d", &arr[i + 1]);
scanf("%d", &arr[i + 2]);
printf("%d, %d, %d\n", arr[i],
arr[i + 1], arr[i + 2]); //serves only to check the input at this point
//at this point I want to send arr 1 to 3 to a function
i += 3;
}
}
The output of this code is a bunch of memory addresses and some of the correct values interspersed. Something like this:
0, 73896, 0
0, 100, -473670944
When it should read:
0, 200, 0
0, 100, 54
int main(){
char c;
while ((c=getchar()) != EOF){
if (c != '\n'){
int a;
scanf("%d", &a);
printf("%d ", a);
}
printf("\n");
}
}
This code prints out the input correctly, but doesn't allow me to use scanf more than once in the while block without a memory problem.
getchar()returns anint, not achar. The code (depending on thesignnessofcharon your compiler) will not recognize EOF. Strongly suggest replacing:char c;withint c;