Adding and Printing elements of an array in C
The problem seems to be here:
for (int i=0; i<200; i++){
fscanf(CFG, "%c", &stringCFG[i]);
howManyItems++;
fprintf(output,"%c", stringCFG[i]);
}
This loop always executes 200 times regardless of what is in the file. In other words - the value of howManyItems
will be 200 when the loop is done.
You can check that simply by printing howManyItems
after the loop, i.e.
printf("After loop, howManyItems=%d\n", howManyItems);
Since you have:
char stringCFG[200];
then
stringCFG[howManyItems]= ','; // bad.. writing to stringCFG[200]
howManyItems++;
stringCFG[howManyItems]= '0'; // bad.. writing to stringCFG[201]
howManyItems++;
...
will write outside of the array. That is undefined behavior.
You need to stop the first loop once the whole file has been read. Something like:
for (int i=0; i<200; i++){
if (fscanf(CFG, "%c", &stringCFG[i]) != 1)
{
// No more data
break;
}
howManyItems++;
fprintf(output,"%c", stringCFG[i]);
}
and all the following loops must then use howManyItems
as the upper limit.
Like
for(int i=0; i<howManyItems; i++){
if(stringCFG[i] == '>'){
RHS= 1;
}
...
}
BTW: Since you want to be able to add 4 extra chars, you probably should do:
char stringCFG[200]; --> char stringCFG[200 + 4];
BTW: Hard-coding the value 200 over and over again is bad practice. Instead use a define like:
#define MAX_CHARS 200
and replace all the hard-coded 200
with MAX_CHARS
. Then you can adjust the maximum simply by editing one line instead of multiple lines.
0 comments:
Post a Comment
Thanks