如何在c中输出char数组

时间:2016-06-04 00:19:07

标签: c

新手在这里, 我正在尝试从txt文件中扫描字符并将其输出到另一个txt文件。我认为我的问题是转换说明符将int转换为char所以我的结果是奇怪的字符。谢谢你的帮助。

#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;
}

更新帖子: 我忘了在同一个文件夹中添加输入文件。我很感激帮助,它有效:)

3 个答案:

答案 0 :(得分:2)

变化

fscanf(lcombo,"%i",&combo[i]);

fscanf(lcombo,"%c",&combo[i]);
扫描字符时

变化

fprintf(lcomboout,"%c \n",&combo[i]);

fprintf(lcomboout,"%c \n",combo[i]);

%c取值,而非地址。

并使用fclose关闭文件。

<强> UPD

代码读取NROW个字符,而不是NROW行,更改为

for (i=0; EOF != fscanf(lcombo,"%c",&combo[i]); ++i);

或使用%s读取行,检查scanf/fscanf的返回值是一种好方法。

您可以保留已成功读取的字符数。例如:

int len;
...
for (len=0; EOF != fscanf(lcombo,"%c",&combo[len]); ++len);
for (i=0; i<len; i++)
    fprintf(lcomboout,"%c \n",combo[i]);
  1. http://en.cppreference.com/w/cpp/io/c/fprintf

答案 1 :(得分:0)

您的代码中有2个错误。

  • 第一个,你自己想出来了。

    fscanf(lcombo,"%i",&combo[i]);

    应该是

    fscanf(lcombo,"%c",&combo[i]);

  • 第二个是基本错误。当你从数组中读取时,你 按值传递参数,而不是通过引用:

    fprintf(lcomboout,"%c \n",&combo[i]);

    应该是

    fprintf(lcomboout,"%c \n", combo[i]);

如果您已阅读编译器发送的警告,则很容易识别这两个错误:

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]);
                       ^

此外,一个好的原则是使用标志-Wall(意思是 W arning:所有)来编译代码,例如:{ {1}}。会引发更多警告。

答案 2 :(得分:0)

像这样解决:

#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]);