请教一个问题:
char *name[]={"1","2"}
int Num ;
txt文件内容如下如下:
"1","2","3","4","5","6"
从文本文件读取这些数据,并读取到name中,并计数结果赋值到Num
请教一个问题:
char *name[]={"1","2"}
int Num ;
txt文件内容如下如下:
"1","2","3","4","5","6"
从文本文件读取这些数据,并读取到name中,并计数结果赋值到Num
利用本人珍藏字符串分解API,直接看代码:
//////////////////////////////////
#include <string>
#include <iostream>
#include <fstream>
#include <streambuf>
#include <memory>
#include <vector>
#include <map>
using namespace std;
/* 字符串分割 API */
int split_s(const std::string& cont, std::vector<std::string>& result, char delim='\t') {
std::size_t new_tok = 0;
std::size_t cur_pos = 0;
result.clear();
for (; cur_pos < cont.size(); ++cur_pos) {
if (cont[cur_pos] == delim) {
std::string token = cont.substr(new_tok, (cur_pos - new_tok) );
if (!token.empty()) {
result.push_back(token);
}
new_tok = cur_pos + 1;
}
}
// 处理结尾
if (new_tok < cont.size()) {
std::string token = cont.substr(new_tok);
if (!token.empty()) {
result.push_back(token);
}
}
return result.size();
}
int main(int argc, char* argv[]) {
string fn = "datafile.txt"; // 默认文件名
if (argc > 1) {
fn = string(argv[1]); // 通过参数传入文件名
}
std::ifstream datf(fn); // 默认文件名
if (!datf) {
std::cout << "Open file FAILED!" << endl;
return -1;
}
/* 对于小文件,可以考虑一次性读入内存 */
std::string name((std::istreambuf_iterator<char>(datf)),
std::istreambuf_iterator<char>());
datf.close();
std::vector<std::string> result;
int num = split_s(name, result, ',');
/* 根据需要输出结果 */
cout << "num :=" << num << endl;
cout << "name :=" << name << endl;
return 0;
}