c - 如何逐字读取文件?
问题描述
我很困惑如何在文件中存在的每个单词之后给出换行符。
文本文件中的单词
Name Date of birth <---- I put this in code
John 02\02\1999 <---- I want to jump to this line
我要这个
Here is your: Name
Here is your: Date of Birth
但它给了我这个
Here is your: N
Here is your: a
Here is your: m
Here is your: e
我不知道如何得到它。
#include <stdio.h>
#include <stdlib.h>
int main(){
FILE * fr = fopen("/home/bilal/Documents/file.txt","r");
char ch;
if(fr != NULL){
while(!feof(fr)){
ch = fgetc(fr);
printf("Here is your %c\n: ", ch);
}
fclose(fr);
}
else{
printf("Unable to read file.");
}
return 0;
}
解决方案
在您的while
循环中,而不是立即打印您读取的字符,将其存储char
在一个char
数组中。添加一个if
执行比较的语句,以检查读取的内容char
是否为空格字符。如果是,您应该打印存储的数组并将数组的索引设置回 0。
例子:
#include <stdio.h>
#include <stdlib.h>
int main(){
FILE * fr = fopen("file.txt","r");
char ch[100];
int index = 0;
if(fr != NULL){
while((ch[index] = fgetc(fr)) != EOF){
//printf("%c\n", ch[index]);
if(ch[index] == ' ') {
ch[index] = '\0';
printf("Here is your: %s\n", ch);
index = 0;
}
else {
index++;
}
}
fclose(fr);
}
else{
printf("Unable to read file.");
}
return 0;
}
推荐阅读
- xml - 聚合 xml 和 xml 列表
- javascript - 通过使用 module.exports 的脚本使用变量不起作用
- r - 如何使用数据集纪念品时间序列执行 ARIMA 测试?
- c++ - 对 const c 数组副本的结构化绑定应该是 const 吗?
- google-chrome-extension - 我可以在 Browserstack 上运行时添加 Chrome 扩展吗?
- protocol-buffers - 在协议缓冲区中替换具有相同类型但含义不同的字段
- angular - Angular 2输入范围最小可变参数
- xml - XSLT For-Each 只选择第一个元素
- php - Eloquent - 由于列转换类型,通过关系删除行失败。如何强制转换类型?
- laravel - 无法使用 Nginx 远程服务器接收来自 PUT 和 DELETE 方法的响应