Reading multiple instances from a file
An answer to this question on Stack Overflow.
Question
So I'm reading from a file where the format has number written out. For example the numbers 1 1 1 2 2. So my output from this file to the user should be 1x3 2x2.
#include<stdio.h>
int main(){
int number;
int times;
FILE* ifp = fopen("counting.txt", "r");
if (ifp == NULL) {
printf("Error opening counting.txt\n");
return 1;
}
while (fscanf(ifp, "%d %d", &number, ×)== 2){
printf( "%dx%d", number, times);
}
return 0;
}
I'm running into a problem where my code above compiles but it isn't returning any output
Answer
Your code did not compile for me.
In fact, your code would not compile for anyone because of this line:
while (fscanf(ifp, "%dx%d" number, times)==2){
There should be a comma before number. I have edited your answer to resolve the problem. However, other compilation errors arise.
It is bad to ask questions about code when that code does not compile, unless you are wondering why it doesn't compile.
Once I fix all of the other bugs in your code, I get this:
#include <stdio.h>
int main(){
int number;
int times;
FILE *ifp = fopen("counting.txt", "r");
while (fscanf(ifp, "%dx%d", number, times)==2){
printf("%d",number);
}
return 0;
}
Note that I've brought the ifp definition inside of main() because globals are bad form. I've also capitalized File because that is how it is defined.
Now, I activate the warnings on my compiler and run this:
gcc bob.c -Wall
Which gives this:
bob.c: In function ‘main’:
bob.c:9:5: warning: format ‘%d’ expects argument of type ‘int *’, but argument 3 has type ‘int’ [-Wformat=]
while (fscanf(ifp, "%dx%d", number, times)==2){
^
bob.c:9:5: warning: format ‘%d’ expects argument of type ‘int *’, but argument 4 has type ‘int’ [-Wformat=]
bob.c:10:17: error: expected expression before ‘%’ token
printf( %d);
Which makes it pretty obvious what's going on.
We fix the problem using this line:
while (fscanf(ifp, "%dx%d", &number, ×)==2){
You'll have to figure out how to finish things out.