C++实现读取文件并转化为string类型及string类型提取int数值

C++实现

1、读取文件并转化为string类型

2、string切割并装入vector数组 

3、string类型提取int数值

直接上代码:

#include <string>
#include <fstream>
#include <sstream>
#include <cstring>
#include <iostream>
#include<vector>
#include <stdlib.h>
using namespace std;


 
//从文件读入到string里
string readFileIntoString(char * filename)
{
ifstream ifile(filename);
//将文件读入到ostringstream对象buf中
ostringstream buf;
char ch;
while(buf&&ifile.get(ch))
buf.put(ch);
//返回与流对象buf关联的字符串
return buf.str();
}

 //string切割放入vector数组
 vector<string> vector_s(string word){
     //用于存放分割后的字符串 
    vector<string> res;
    //待分割的字符串,含有很多空格 
    //string word = "   Hello, I want   to learn C++!   ";
    //暂存从word中读取的字符串 
    string result;
    //将字符串读到input中 
    stringstream input;
    input << word;
    //依次输出到result中,并存入res中 
    while (input >> result)
        res.push_back(result);
//    //输出res 
//    for (int i = 0; i < res.size(); i++) {
//        cout << res[i] << endl;
//    }
    return res;
 }
 
 
 
 //转换为数字 
int shuzi(char a[]){
 
    char b[50];
    int cnt_index = 0, cnt_int = 0;
    //cnt_int 用于存放字符串中的数字.
    //cnt_index 作为字符串b的下标.

    for (int i = 0; a[i] != '\0'; ++i) //当a数组元素不为结束符时.遍历字符串a.
    {
        if (a[i] >= '0'&& a[i] <= '9') //如果是数字.
        {
            cnt_int *= 10;//先乘以10保证先检测到的数字存在高位,后检测的存在低位
            cnt_int += a[i] - '0'; //数字字符的ascii-字符'0'的ascii码就等于该数字.
        }

        else //如果是其他字符.
        {
            b[cnt_index++] = a[i]; //如果是字符,则增加到b数组中.
        }
    }

    b[cnt_index++] = '\0'; //增加字符串结束符.

    //cout << b << endl; //输出字符串. 

    return cnt_int;
}
 
//循环数组
void for_data(int t_data[]){
	for(int i = 1;i<100;i++){
		cout << t_data[i] << endl;
	}
}
 
 

int main(){

//文件名
char * fn="E:/长师学习/C++/3.7/data.txt";
string str;
str=readFileIntoString(fn);
cout<<str<<endl;
vector<string> res= vector_s(str);
vector<int> data;
int max_day = 0;
string::size_type idx;
string::size_type idx1;
	
    for (int i = 0;i<res.size();i++){
    	idx = res[i].find("确诊病例");
    	idx1 = res[i].find("出院病例");
    	if(idx != string::npos | idx1 != string::npos){
    		char dst[255];
    		//string转换为char[] 
    		strcpy(dst,res[i].c_str());
    		//cout <<dst<< endl;
    		int accumula = shuzi(dst);
    		//cout <<dst<< endl;
    		data.push_back(accumula);
    			}		
    		}
    int max_chuyuan=0;//最大出院人数 
	int max_xinzeng=0;//最大新增人数 
	int chuyuan_index=0;//最大出院人数下标 
	int xinzeng_index=0;	//最大新增人数下标
	
	//逻辑判断 
	for(int i=2;i<data.size();i++){
			if(i%2 == 0){
					if(data[i-2]-data[i]>max_xinzeng){
						max_xinzeng = data[i-2]-data[i];
							xinzeng_index=i*3-6;
					}	
			}else{
				if(data[i-2]-data[i]>max_chuyuan){
						max_chuyuan = data[i-2]-data[i];
							chuyuan_index=(i-1)*3-6;
					}
			}
	}	
	cout <<res[xinzeng_index]+",新增病例最多,其人数为:"<<max_xinzeng<< endl;
	cout <<res[chuyuan_index]+",治愈出院病历最多,其人数为:"<<max_chuyuan << endl;
		
system("pause");
 
}
原创文章 7 获赞 34 访问量 3万+

猜你喜欢

转载自blog.csdn.net/qq_37377691/article/details/105795969