怎么样从txt文本中读取多行内容?

huaxin84 2011-08-20 10:02:52
如题,我的思路是:


const int max = 100
string words[max];
RtlZeroMemory(words,sizeof(words));
string zs[max];
RtlZeroMemory(words,sizeof(zs));
int a =50; //假设文本每行50个字符,两个内容用空格分开
ifstream fin ("date.txt");
if (!fin.bad())
{
for(int n = 0; n<50; n++)
{
fin.ignore( a , '^');
fin>>words[n]>>zs[n];
a+=50
}
fin.close();
}

ofstream fout ("date2.txt");
if (!fin.bad())
{
fout<<""<<endl
<<setw(20)<<words[0]<<setw(30)<<zs[0]<<endl;
fout.close();
}





但是没用成功,不知为什么。求解
...全文
201 10 打赏 收藏 转发到动态 举报
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
shaotine_wu 2011-08-21
  • 打赏
  • 举报
回复
用getline后,再使用istringstream,把一行的两个字符串分别取出放在你想要的数组中。
示例如下:

istringstream istr;
string first,second;
for(int i=0;i<n;i++)
{
fin.getline(words,20);//这里是读取一行的前20个字符。放入words中
istr(words);
istr>>first; //取到的是你文件中的一行的第一个字符串,放入first中
istr>>second;//取到第二个字符串,放入second中
}

再不懂LZ可以google下istringstream和getline的用法
huaxin84 2011-08-21
  • 打赏
  • 举报
回复
[Quote=引用 5 楼 ywwj5858792qd 的回复:]

ifstream fin ("date.txt");
int n=4; //n为你的行数
for(int i=0;i<n;i++)
{
fin.getline(words,20);
cout<<words<<endl;
}
[/Quote]

fin.getline(words,20);什么意思啊,我要把两个内容赋值给words[i]和zs[i]




huaxin84 2011-08-21
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 ywwj5858792qd 的回复:]

fin.ignore( a , '^');
这个用的不对吧
MSDN:
ignore( int nCount = 1, int delim = EOF );
Extraction stops if the delimiter delim is extracted or the end of file is reached
这个函数意思是,要么忽略前nCount个字符或者遇到后面的del……
[/Quote]


我是要忽略已经读过的~
huaxin84 2011-08-21
  • 打赏
  • 举报
回复
getline具体怎么用啊 ~?

AndyZhang 2011-08-21
  • 打赏
  • 举报
回复
getline,果断
ywwj5858792qd 2011-08-20
  • 打赏
  • 举报
回复
#include<iostream>
#include <fstream>
#include <string>

using namespace std;

int main()
{
const int max = 100;
char words[max]={0};
//RtlZeroMemory(words,sizeof(words));
char zs[max]={0};
//RtlZeroMemory(words,sizeof(zs));
int a =50; //假设文本每行50个字符,两个内容用空格分开
ifstream fin ("date.txt");
int n=4; //n为你的行数
for(int i=0;i<n;i++)
{
fin.getline(words,20);
cout<<words<<endl;
}


return 0;
luciferisnotsatan 2011-08-20
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 ywwj5858792qd 的回复:]

用getline()
[/Quote]
++
一行一行读
ywwj5858792qd 2011-08-20
  • 打赏
  • 举报
回复
fin.ignore( a , '^');
这个用的不对吧
MSDN:
ignore( int nCount = 1, int delim = EOF );
Extraction stops if the delimiter delim is extracted or the end of file is reached
这个函数意思是,要么忽略前nCount个字符或者遇到后面的delim 停止忽略,就看哪个条件先满足了。
ywwj5858792qd 2011-08-20
  • 打赏
  • 举报
回复
用getline()
huaxin84 2011-08-20
  • 打赏
  • 举报
回复
文本是类似这样:
(50个空格)
(20个空格)moon(22个空格)月亮
(21个空格)sun(22个空格)太阳

能不能具体讲解一下fin.ignore();

64,650

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

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