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");
 
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章