背景:WIndows下利用C++ 从文件中读写内容
1、使用fscanf语句
#include <map>
#include <fstream>
std::FILE *fp;
fp = fopen(filePath.c_str(), "r");
if (!fp ) {
printf("Cann't open input csv file: %s\n", filePath);
return 0;
};
std::map<std::string,std::string> NoNameMap;
fscanf(fp, "%s,%s,%s", &a, &b, &c);
printf("%s %s %s\n", a, b, c);
while (1){
std::string first, second,temp;
fscanf(fp, "%s,%s,%s", &first, &second, &temp);
printf("%s %s %s\n", first, second,temp);
NoNameMap.insert(std::pair<std::string, std::string>(first, second));
if(feof(fp)) //判断是否到文件结尾
break;
}
fclose(fp);
注意:执行到 NoNameMap.insert 这一步。总是出现异常:内存错误 std::bad_alloc,目前没有解决方法
2、使用getLine函数
std::ifstream f(filePath);
std::string csvLine;
getline(f, csvLine);//第一行表头不做统计
while (getline(f, csvLine))