Reputation: 521
Newbiee here, I am trying to scan characters from a txt file and output it to another txt file. I think my problem is conversion specifiers converting int to char so my result is weird characters. Thanks for your help.
#include <stdio.h>
#define NROW 676
#define FILEIN "lettercombo.txt"
#define FILEOUT "lettercomboout.txt"
int main(void) {
//Variables
int i;
char combo [NROW];
FILE *lcombo;
FILE *lcomboout;
//Writes output file or overwrites previous one
lcomboout = fopen(FILEOUT,"w");
// Open file and read data into array
lcombo = fopen(FILEIN,"r");
for (i=0; i<677; i++)
fscanf(lcombo,"%c",&combo[i]);
for (i=0; i<677; i++)
fprintf(lcomboout,"%c \n",combo[i]);
return 0;
}
Update post: I forgot to add the input file in the same folder. I appreciate the help, it works :)
Upvotes: 0
Views: 308
Reputation: 40145
fix like this:
#define NROW 676 // 26*26 : [A-Z] * [A-Z]
//...
//Variables
int i;
char combo[NROW][2];
//...abridgement
for (i=0; i<NROW; i++)
fscanf(lcombo," %2c", combo[i]);//fscanf(lcombo," %c%c", &combo[i][0], &combo[i][1]);
for (i=0; i<NROW; i++)
fprintf(lcomboout, "%c%c\n", combo[i][0], combo[i][1]);
Upvotes: 0
Reputation: 3818
change
fscanf(lcombo,"%i",&combo[i]);
to
fscanf(lcombo,"%c",&combo[i]);
as you scan chars.
change
fprintf(lcomboout,"%c \n",&combo[i]);
to
fprintf(lcomboout,"%c \n",combo[i]);
%c
takes a value, not address.
and use fclose
to close the file.
UPD
The code reads NROW
chars, not NROW
lines, change to
for (i=0; EOF != fscanf(lcombo,"%c",&combo[i]); ++i);
or use %s
to read lines, it is good manner to check return value of scanf/fscanf
.
And you can keep how many chars has been successfully read. For example:
int len;
...
for (len=0; EOF != fscanf(lcombo,"%c",&combo[len]); ++len);
for (i=0; i<len; i++)
fprintf(lcomboout,"%c \n",combo[i]);
Upvotes: 2
Reputation: 169
You have 2 errors in your code.
The first one, you figured it out by yourself.
fscanf(lcombo,"%i",&combo[i]);
should be
fscanf(lcombo,"%c",&combo[i]);
The second one is a basic mistake. When you read from the array, you pass arguments by value, not by reference:
fprintf(lcomboout,"%c \n",&combo[i]);
should be
fprintf(lcomboout,"%c \n", combo[i]);
.
Both of those mistakes would be easily identified if you had read the warnings sent by the compiler:
main.c: In function ‘main’:
main.c:20:19: warning: format ‘%i’ expects argument of type ‘int *’, but argument 3 has type ‘char *’ [-Wformat=]
fscanf(lcombo,"%i",&combo[i]);
^
main.c:23:27: warning: format ‘%c’ expects argument of type ‘int’, but argument 3 has type ‘char *’ [-Wformat=]
fprintf(lcomboout,"%c \n",&combo[i]);
^
Also, it is a good principle is to use the flag -Wall
(meaning Warning:all) to compile your code, for example: gcc -Wall my_program.c -o my_program
. A lot more warnings will raise.
Upvotes: 0