如何用C++语言实现读取txt文件,并对数据进行解析

popofay 2011-10-20 04:20:09
求助~如何用C++语言读取txt文件,并对数据进行解析~!

这是存在txt文件里的数据GOTO/175,777,45.00,89,12,34
现在想把GOTO和后面的数据分开存储,并继续将后面六个数据分别用六个变量进行存储,以便用于下一步处理。

求高手帮忙~急~~
...全文
694 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
小湿哥 2011-10-20
  • 打赏
  • 举报
回复

运行结果。。


这个必须也要推荐。嘎嘎。
http://download.csdn.net/detail/jacicson1987/3691515
小湿哥 2011-10-20
  • 打赏
  • 举报
回复

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
int main ()
{
string file("go.txt");//txt文件。
ifstream input(file.c_str());
vector<double> val;
char ch;
double dval = 0;
for(int i= 0; i != 5; ++i)//此循环使文件指针指向“/”后,也就是跳过goto/部分
input >> ch;
while (input >> dval,true)//读入每个变量至 double型 dval中,并通过dval读入vector<double> val容器中。
{
if(input.bad())
throw std::runtime_error("IO stream corrupted");
if(input.fail())
{
if(input.eof())break;
input.clear();
input.ignore(1,',');
continue;
}
val.push_back(dval);

}
input.clear();
for(vector<double>::const_iterator it = val.begin(); it != val.end() ; ++it)//输出容器中的变量。
cout << *it << ' ';
cout << endl;
return 0;
}
turing-complete 2011-10-20
  • 打赏
  • 举报
回复
周晓荣 2011-10-20
  • 打赏
  • 举报
回复

#include <iostream>
#include <string>
#include <fstream>
using namespace std;

void GetData(string *p_array)
{
ifstream in("test.txt");//你那文件的路径
if(!in)
{
exit(0);
}
string str_file_content,str_content,str_type,addressLine;
while( getline(in, str_file_content) )
{
int index = str_file_content.find_first_of('/');
str_type = str_file_content.substr(0,index);
str_content = str_file_content.substr(index+1, str_file_content.length());
if ("GOTO" == str_type)
{
index = str_content.find_first_of(',');
while(string::npos != index)
{
*p_array = str_content.substr(0, index);
str_content = str_content.substr(index+1, str_content.length());
index = str_content.find_first_of(',');
++p_array;
}
*p_array = str_content;
}
}
}
int main(void)
{
string test[6];
GetData(test);

for(int i = 0;i <6; ++i)
cout<<test[i]<<endl;

system("pause");
return 0;
}
追求执着 2011-10-20
  • 打赏
  • 举报
回复
有点数据挖掘的味道,这要固定的格式文本吧,坐等楼下解答
gfy5216 2011-10-20
  • 打赏
  • 举报
回复
建议使用流和容器

64,654

社区成员

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

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