记一道读文件的题(按行读,split(),atoi())

    一直读文件的操作不慎熟悉,每次涉及都是现查。这次写下这一题,希望这一类型的不再忘。


题目:从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;
	

}


find 函数:


(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




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值