懂文件读写的高手进来看看

cplusplusman 2003-12-14 11:35:19
有这样一个文本文档:
1 3
3 4
4 6
##
想读取文件中的数据,一行为一单元,直到有##停止,应该用什么读写函数比较好,提示点思路,1 3后面那么多空格才到3 4应该怎么做读到呢?我比较菜,请各位给点详细的解释,不慎感激。
...全文
100 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
junnyfeng 2003-12-14
  • 打赏
  • 举报
回复
把老徐的改良一下,会运行得更好

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

void main()
{
long a, b;
char astr[256], bstr[256];
FILE * fp;

fp = fopen("test.txt", "r");
while (!feof(fp))
{
fscanf(fp, "%s %s", astr, bstr);
if (strcmp(astr, "##")==0)
break;
a = atoi(astr);
b = atoi(bstr);
if(strcmp(bstr, "##")==0)
{

printf("%d",a);
break;
}

printf("%d, %d, ", a, b);
}
fclose(fp);
}

i_jianyong 2003-12-14
  • 打赏
  • 举报
回复
// C++ 版本
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main()
{
ifstream ifs("data.txt);
string s1, s2;
while (ifstream >> s1 >> s2)
{
if (s1 == "#" && s2 == "#")
break;
cout << s1 << ' ' << s2 << endl;
}
}
junnyfeng 2003-12-14
  • 打赏
  • 举报
回复
你怎么说后面有很多空格呢?都是你放的啊? 说不定是个回车呢。

如果内容不太规则,可以用fgetc()
如果只是针对你上面的结构,可以用如下的程序

#include <stdio.h>

void main()
{
FILE *fp;
char a,b;
fp=fopen("test.txt","r");// 假定文本为test.txt
do{

fscanf(fp,"%c%c",&a,&b); // 读文件
printf("%c%c",a,b);
}while(a!='#' && b!='#');
}
smalltalk 2003-12-14
  • 打赏
  • 举报
回复
int a, b;
char astr[256], bstr[256];
FILE * fp;

fp = fopen("filename.txt", "r")
while (!feof(fp))
{
fscanf(fp, "%s %s", astr, bstr);
if (strcmp(astr, "#")== 0)
break;
a = atoi(astr);
b = atoi(bstr);
printf("%d, %d", a, b);
}
fclose(fp);
KingI 2003-12-14
  • 打赏
  • 举报
回复
把 junnyfeng(阳光少年) 的稍稍修改了一下
#include <stdio.h>

void main()
{
FILE *fp;
char a,b;
fp=fopen("test.txt","r");
fscanf(fp,"%c%c",&a,&b);
while (a!='#' && b!='#')
{
printf("%c%c",a,b);
fscanf(fp,"%c%c",&a,&b);

}
}
koskinen 2003-12-14
  • 打赏
  • 举报
回复
#include<fstream>
#include<iostream>
#include<vector>
#include<sting>
using namespace std;
void main()
{
ifstream in("你的文件");
string line;
vector<string> lines; //string类容器;
while(getline(in,line)&&line!="##")
{
lines.push_back(line);
}
//这里可以添加你自己的代码;比如输出到屏幕
}

zhangfjj 2003-12-14
  • 打赏
  • 举报
回复
用fscanf函数呀

70,035

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧