您的位置:首页 > 其它

从txt文件读取内容并进行字符串分割

2017-04-24 16:45 429 查看
话不多说,直接上源码:

#include <iostream>
#include <string>
#include <vector>
#include <stdlib.h>   //用atoi函数必须包含的头文件
#include <fstream>  //用ifstream必须包含的头文件

using namespace std;
vector<string> strSplit(string, string);

vector<string> strSplit(string mystr, string split_char){
vector<string> strs;
size_t index = 0;       //size_t是无符号整数,其中定义了特殊的标识:npos。当find()函数查找失败时,返回npos用size_t类型的变量接受
int lastPosition = 0;    //用于分割字符串
int initialSize = mystr.size();
cout << mystr.size() << endl;

while(mystr.size() != 0){
index = mystr.find(split_char);
if(index != string::npos){
strs.push_back(mystr.substr(lastPosition, index));
mystr = mystr.substr(index + 1, initialSize);
initialSize = mystr.size();
}
else{
strs.push_back(mystr);
break;
}
}
return strs;
}

int main(){

ifstream in("text.txt");   //绝对路径或者相对路径
string mystr1;
string mystr;
while(getline(in,mystr1)){
cout << mystr1.c_str() << endl;
mystr = mystr1;    //如果没有这行赋值,离开这个循环,mystr1还是空的
}

string split_char = ",";
vector<string> strs = strSplit(mystr, split_char);

//cout << strs.size() << endl;
int num[5];

for(size_t i = 0; i < strs.size(); i++){
num[i] = atoi(strs[i].c_str());
}

for(int i = 0; i < 5; i++){
cout << num[i] << '\t';
}
return 0;
}


如果不通过单独写函数的形式也可以实现文件数据的读取和转型:

#include <iostream>
#include <stdio.h> //sscanf的头文件
#include <string>
#include <fstream>

using namespace std;

int main(){
//string mystr = "20 12 54 75";
ifstream in("text.txt");
string mystr, mystr1;
while(getline(in,mystr1)){
cout << mystr1.c_str() << endl;
mystr = mystr1; //如果没有这行赋值,离开这个循环,mystr1还是空的
}

cout << "method 1:" << endl;
int num[4];
sscanf(mystr.c_str(),"%d %d %d %d", &num[0], &num[1], &num[2], &num[3]); //method1 通过sscanf的方式也可以格式化分割,此时文件中的数据是用空格分开的
for(int i = 0; i < 4; i++){
cout << num[i] << '\t';
}
cout << endl;

cout << "method 2:" << endl;
ifstream inn("text.txt");
int num2[4];
for(int i = 0; i < 4; i++){
inn >> num2[i]; //通过逐项写入的方式,这两种方法都是必须知道要写如项的个数
}
for(int i = 0; i < 4; i++){
cout << num2[i] << '\t';
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: