【发布时间】:2014-05-06 14:19:53
【问题描述】:
嗨。 我需要读取几个字符之间没有空格或空行的文件。它们可以有不同的布局,例如 1.txt、2.txt 或 3.txt:
1.txt:
t
h
i
s
f
i
l
e
2.txt:
l
i
k
e
t
h
a
t
3.txt:
s o m e t h i n g
l i k e
t h a t
我该怎么做?我只有以下代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(){
char c ;
FILE *fp;
fp = fopen("1.txt","r");
if(fp == NULL){
puts("Open file failed\n");
exit(-1);
}
while(fscanf(fp,"%c\n",&c)!=EOF){
/*do things with c var*/
}
fclose(fp);
exit(0);
}
【问题讨论】:
-
while ((c = fgetc(fp)) != EOF) { if (isspace(c)) 继续; ... }
-
不要使用 fscanf,像 kusma 建议的那样使用 fgetc。然后检查空格(空格、换行符、制表符)并存储或输出字符是否正常
-
像 kusma 建议的那样:使用
fgetc,并将c的类型更改为int,因为这是fgetc返回的内容 -
好的,谢谢。它就像我想要的那样工作。
-
其他问题.. 而且,在其他情况下,如果我有单词而不是字符并且我一行中只有一个单词?也就是说,它们之间没有空行的单词。