Post the code you have so far -- remember to use code tags : [code][/code].
Dave Sinkula
long time no c
5,058 posts since Apr 2004
Reputation Points: 2,780
Solved Threads: 314
In C, it may be better not to cast the return value of malloc.
grid = (char *)malloc(sizeof(char) * 9 * 9);
Checking the return value is always recommended. As is here.
f_read = fopen(argv[1], "r");
Checking return values will save you countless hours of debugging, so it's a good habit to start. Unless you like to pull your hair out for hours.
This line was missing a {.
for ( t = 0; t <50; t++ )
Here is a place to fix up:
while ( (num = fscanf(f_read, "%c", tempGrid))!= EOF )
I might go with something more like this.
for ( i = 0; i < 50 && fscanf(f_read, "%c", &tempGrid[i]) == 1; i++ )
You are only reading into the first element of tempGrd. Later you pretend you have filled the whole thing up.
grid[i] = tempGrid[i];
Multiplying bysizeof(char) is the long way of multiplying by one, which is pointless.
If the number of characters in the file may be less than your 50, it might be wise only to print out as many as were read.
Take another swing and we'll move forward from there.
Dave Sinkula
long time no c
5,058 posts since Apr 2004
Reputation Points: 2,780
Solved Threads: 314
for ( i = 0; i < 50 && fscanf(f_read, "%c", &tempGrid[i]); i++ )
Could you explain that line a bit?
I don't really undestand how "i <50 && fscanf..." part works
It just has two conditions to continue the loop -- that you don't overflow the buffer and that you successfully read some data (in the edited and fixed version the return value offscanf is compared to 1).
And also the malloc line was given to us by the prof. He said that we have to use that exact line. He said it's his way of making sure we don't use a 2D array for the assignment :p
[sarcasm=thin]Great -- another professor who needs a few more lessons.[/sarcasm]
Dave Sinkula
long time no c
5,058 posts since Apr 2004
Reputation Points: 2,780
Solved Threads: 314
You seem engaged in this, so I'll post my working copy.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int main(int argc, char *argv[])
{
char *grid = malloc(9 * 9);
if ( grid )
{
int t, i = 0;
if ( argc > 1 )
{
FILE *f_read = fopen(argv[1], "r");
if ( f_read )
{
char tempGrid[50];
puts("Just before while");
while ( i < 50 && fscanf(f_read, "%c", &tempGrid[i]) == 1 )
{
if ( tempGrid[i] != ',' && !isspace(tempGrid[i]) )
{
grid[i] = tempGrid[i];
++i;
}
}
}
}
for ( t = 0; t < i; t++ )
{
printf("%c\n", grid[t]);
}
free(grid);
}
return 0;
}
/* my output
H:\test>test file.txt
Just before while
9
8
5
4
7
3
1
5
*/
Dave Sinkula
long time no c
5,058 posts since Apr 2004
Reputation Points: 2,780
Solved Threads: 314