一直读文件的操作不慎熟悉,每次涉及都是现查。这次写下这一题,希望这一类型的不再忘。
题目:从test.txt中计算第三列的和。
test.txt:
张三 女 5000 北京
李四 女 3000 上海
王五 男 5000 成都
#include <cstdio>
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int atoi(string str){
char a[str.size()];
strncpy(a, str.c_str(), str.size());
int sum = 0;
for(int i = 0; i < str.size(); i++){
sum = sum * 10 + (a[i] - '0');
}
return sum;
}
int split(string str, char val){
int pos;
int npos;
int count = 0;
string str0;
while((npos = str.find(val, pos)) != -1){ //str.find()在查找字符时,参数一是查找字符,参数二是起始位置,返回查找到的位置
str0 = str.substr(pos, npos - pos);
count ++;
pos = npos + 1;
if(count == 3)
return atoi(str0);
}
return 0;
}
int main(){
ifstream infile("./input.txt");
string str;
int sum = 0;
while(getline(infile, str)){
int m = split(str,' ');
cout << m << endl;
sum += m;
}
cout << "sum :"<< sum << endl;
}
(1)size_t find (const string& str, size_t pos = 0) const; //查找string类对象
(2)size_t find (const char* s, size_t pos = 0) const; //查找字符串
(3)size_t find (const char* s, size_t pos, size_t n) const; //查找字符串的前n个字符
(4)size_t find (char c, size_t pos = 0) const; //查找字符
找到返回 第一个字符的索引
没找到返回 string::npos