对.txt文件操作,每次读取一行,并对这一行字符串截取,并将截得的字符串直接转为数值型,该怎么处理
对.txt文件操作,每次读取一行,并对这一行字符串截取,并将截得的字符串直接转为数值型
我想要编一个对.TXT文件进行只读的操作.
就是每次从.txt中读出一行字符串,例如"3,5,12,30"
然后对这个字符串截取,分别取出"3","5","12","30"
然后将这些字符串转换成数值型并能进行数学的计算.如3*10+5*10+12*10+30*10
请大侠们给看看,教教俺呗
------解决方案--------------------
c++语言的输入默认是以空格为分隔符的,所以如果测试文件内容是以空格分隔而不是以逗号分隔的话,
则以下程序运行正常。
我想要编一个对.TXT文件进行只读的操作.
就是每次从.txt中读出一行字符串,例如"3,5,12,30"
然后对这个字符串截取,分别取出"3","5","12","30"
然后将这些字符串转换成数值型并能进行数学的计算.如3*10+5*10+12*10+30*10
请大侠们给看看,教教俺呗
------解决方案--------------------
c++语言的输入默认是以空格为分隔符的,所以如果测试文件内容是以空格分隔而不是以逗号分隔的话,
则以下程序运行正常。
- C/C++ code
#include <iostream> #include <fstream> #include <string> #include <sstream> #include <vector> #include <numeric> #include <functional> #include <algorithm> using namespace std; void main() { // open file ifstream infile("test.txt", ios_base::in); if (!infile) { cout << "open file test.txt failed!" << endl; return; } do { int i, sum = 0; string strline; vector<int> vi; // read one line data each time getline(infile, strline); istringstream ii(strline); // parsing each integer value from istringstream, and // push it in a vector container while (ii >> i) vi.push_back(i); // parsing ok, transform the value as you like, here multiplies it with 10 transform(vi.begin(), vi.end(), vi.begin(), bind1st(multiplies<int>(), 10)); // compute the sum of all elements in vector sum = accumulate(vi.begin(), vi.end(), 0, plus<int>()); // output result cout << sum << endl; } while (!infile.eof()); infile.close(); }
------解决方案--------------------
大概写了一下
[code=C/C++][/code]#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
string badchars=","; //定义分隔符,可以是任意的分隔符
//如果要把算术运算符作为分隔符可以把它赋值为
//string badchars="+-*/";
//用来从字符串中取出用标记符分割的子字符串
string next_token(const string &s, int& pos)
{
int begin=s.find_first_not_of(badchars,pos);
int end=s.find_first_of(badchars,begin);
pos=end;
if(begin==string::npos)
return string();
else if(end==string::npos)
return s.substr(begin);
else
return s.substr(begin,end-begin);
}
int strtoint(string str)
{
char buf[20];
int value1;
int i=0;
for(i=0;i<str.size();i++)
{
//if(str[i]=='/')
// break;
buf[i]=str[i];
}
buf[i]='\0';
value1=atoi(buf);
return value1;
}
void main()
{
vector<int> ivec;
ifstream infile("1.txt");
int pos=0;
string str1;
while(!infile.eof())
{
pos=0;
getline(infile,str1);//取出文本文件中的一行
string str=next_token(str1,pos);
int a=strtoint(str); //将字符串转化为整形
ivec.push_back(a);
while(str!="")
{
str=next_token(str1,pos);
int a=atoi(str);
ivec.push_back(a);
} //ivec 中记录了每个整形数
}
}