文件读取问题

xjxy 2007-03-19 08:44:00
准备从文件中读取一些内容,文件如下:
test1 hello 34 test2 43 test3 45
test2 orange 32
...................
格式就是如此,但是每行长度不定,包含内容个数也不同,想把每行读出后再将其中内容分割出来:
test1
hello 34
test2 43
test3 45

test2
orange 32
。。。。。。。。。。。。。
试了sscanf等函数,但是由于水平问题效果达不到,求教各位大侠,谢谢。
...全文
238 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
redstorm_fyy 2007-03-20
  • 打赏
  • 举报
回复
while(fgets(line,sizeof(line),fp))
{
//deal one line
}
xjxy 2007-03-20
  • 打赏
  • 举报
回复
那位大侠告知?万分感谢!!
xjxy 2007-03-20
  • 打赏
  • 举报
回复
郁闷,
..............
int i = 0;
char c;
while((p=fgets(buff, MAXLINE, ifp)) != NULL)
{
while(buff[i] != '\0')
c = buff[i++];
}
竟然来了个:Segmentation fault
高手给个解决方案吧!谢谢
FingerStyle 2007-03-20
  • 打赏
  • 举报
回复
hohoho
todototry 2007-03-20
  • 打赏
  • 举报
回复
okokok
xjxy 2007-03-20
  • 打赏
  • 举报
回复
这样是可以区分每一行,但是取出来的是一个字符串数组,而且由于每行中元素个数不定,好像sscanf也用不了,只有一个一个字符的区分了
xjxy 2007-03-19
  • 打赏
  • 举报
回复
忘了说一句,我想用c来实现,谢谢
tuhuo 2007-03-19
  • 打赏
  • 举报
回复
try stringstream
believefym 2007-03-19
  • 打赏
  • 举报
回复
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main()
{
ifstream is("test.txt");
string line;
while(getline(is,line))
{
//cout<<line<<endl;
char h[10]={0};
char t[10]={0};
char d[10]={0};
sscanf(line.c_str(),"%s",h);
cout<<h<<endl;
int i=strlen(h)+1;
while(1)
{
if(i>=line.length())
break;
sscanf(line.c_str()+i,"%s%s",t,d);
cout<<" "<<t<<" "<<d<<endl;
i+=strlen(t)+strlen(d)+2;
}
cout<<endl;
}
system("pause");
return 0;
}

69,382

社区成员

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

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