如何读取txt文件中的数据

linkpix 2008-10-30 05:42:20
一个txt文件中有一些数据如下:
savings 123 70000
checking 661 20000
savings 128 2000
savings 131 5000
checking 681 200000
checking 688 10000
x 0
要求读取的时候先按行读入,再判断是savings还是checking 之后分类,分别读出后面的2个数字
例如 第一行 先判断是savings 读出 123和700002个数字,分别存储,并把字符串转换成数字,
之后再读第二行,遇见x 0的时候停止
急求 用文件流处理,代码不要太复杂,谢谢。
...全文
147 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
Jacky_Dai 2008-10-30
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 wuyu637 的回复:]
int main()
{
ifstream infile;
infile.open("data.txt",ios::in);

char buffer[200];
char *cMark = new char[200];
while(infile.getline(buffer,200))
{
if(strstr(buffer,"x  0"))
{

cout < < "this is the end of file" < < endl;
break;
}
if(strstr(buffer,"savings"))
{

cout < < " this is saving " < < endl;

strtok(buffer, " ");
cMark = strtok(NULL," ");
int number1 = atoi(cMark…
[/Quote]
呵呵! 不错!
wens07 2008-10-30
  • 打赏
  • 举报
回复


#include<iostream>
#include<fstream>
#include<string>
#include<vector>

using namespace std;


//用于存储两个数据
struct inf
{
int n;//第一个数据
int v;//第二个数据
};

void main()
{

ifstream cin("a.txt");
string s;
vector<inf> save;//用于存储savings的数据
vector<inf> check;//用于存储checking的数据

while(cin>>s)
{
inf f;
if(s=="x")
break;
cin>>f.n>>f.v;

if(s=="savings")
save.push_back(f);
if(s=="checking")
check.push_back(f);


}



}


sxxiaozi 2008-10-30
  • 打赏
  • 举报
回复
while(file.ReadString(str))
{
处理str
}
把txt中的一行存到str中,楼主就可以处理了
处理完会自动取下一行
wuyu637 2008-10-30
  • 打赏
  • 举报
回复
int main()
{
ifstream infile;
infile.open("data.txt",ios::in);

char buffer[200];
char *cMark = new char[200];
while(infile.getline(buffer,200))
{
if(strstr(buffer,"x 0"))
{

cout << "this is the end of file" << endl;
break;
}
if(strstr(buffer,"savings"))
{

cout << " this is saving " << endl;

strtok(buffer, " ");
cMark = strtok(NULL," ");
int number1 = atoi(cMark);
cout << "the first number is " << number1 << endl;
cMark = strtok(NULL," ");
int number2= atoi(cMark);
cout << " the second number is " << number2 << endl;
//delete []cMark;
}
if(strstr(buffer,"checking"))
{
cout << " this is checking " << endl;
//char* cMark= new char [100];
strtok(buffer, " ");
cMark = strtok(NULL," ");
int number1 = atoi(cMark);
cout << "the first number is " << number1 << endl;
cMark = strtok(NULL," ");
int number2= atoi(cMark);
cout << " the second number is " << number2 << endl;
//delete []cMark;
}


}
delete[]cMark;
}

64,682

社区成员

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

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