c++中如何提取文件每一行的一部分

图片说明
以下是我写的一段程序,可是编译时却出现了

error C2664: 'void __thiscall std::basic_ifstream >::open(const char *,int)' : cannot convert parameter 1 from 'class std::basic_string har,struct std::char_traits,class std::allocator >' to 'const char *'
No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called
执行 cl.exe 时出错.

很苦恼,希望各路大神指教

我写的程序:
#include
#include
#include
#include
using namespace std;

int main()
{
vector vec_num;
string filename,line;
cout << "请输入要处理的图像路径:" << endl;
cin >> filename;
ifstream file;
file.open(filename);
if (!file.is_open())
{
cout << "有错误!文件未被打开\n";
}
while(getline(file, line))
{
float first_num,second_num;
int third_num;
sscanf(line.c_str(), "%f %f %d", &first_num, &second_num, &third_num);//格式化提取
cout << first_num << " " << second_num << " " << third_num << endl;//打印一下数据
//用vector把第一列的数据存下来
vec_num.push_back(first_num);
}

float avg_num = 0.0;//保存计算出来的平均数结果
//遍历vector
vector::iterator it;
for(it = vec_num.begin(); it != vec_num.end(); it++)
{
avg_num += *it;
}
avg_num = avg_num / vec_num.size();
cout << "第一列平均数是:" << avg_num << endl;
system("pause");
return 0;
}

首先,filename,line应该定义为char类型;其次,vector使用需要制定类型;最后getline用法不对。
#include
#include
#include
using namespace std;
int main()
{
vector vec_num;
char filename[256],line[256];
cout << "请输入要处理的图像路径:" << endl;
cin >> filename;
ifstream file(filename);

if (!file.is_open())
{
    cout << "有错误!文件未被打开\n";
    return 0;
}

while (!file.eof())  
{  
    file.getline (line,256);  
    float first_num,second_num;
    int third_num;
    sscanf(line, "%f %f %d", &first_num, &second_num, &third_num);//格式化提取
    cout <<"first_num:"<< first_num << "second_num: " << second_num << "third_num: " << third_num << endl;//打印一下数据
    //用vector把第一列的数据存下来
    vec_num.push_back(first_num);
}  

float avg_num = 0.0;//保存计算出来的平均数结果
//遍历vector
vector<float>::iterator it;
for(it = vec_num.begin(); it != vec_num.end(); it++)
{
    avg_num += *it;
}
avg_num = avg_num / vec_num.size();
cout << "第一列平均数是:" << avg_num << endl;
system("pause");
return 0;

}

http://www.cnblogs.com/freeliver54/archive/2012/06/18/2554173.html

我认为加一个c语言会好一些,当然我是个菜鸟

我认为加一个c语言会好一些,当然我是个菜鸟

我认为加一个c语言会好一些,当然我是个菜鸟

提取的时候,那些数据是 未知的,scanf 是字符拼接的吧,是不是用的不对

最简单的解决办法是把 vs2010中的项目-》项目属性-》general-》把using unicode改成Use Multi-Byte Character Set。
稍微麻烦一点的办法是把string转换格式成char*

error C2664: 'void __thiscall std::basic_ifstream >::open(const char *,int)' : cannot convert parameter 1 from 'class std::basic_string har,struct std::char_traits,class std::allocator >' to 'const char *'
No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called

解决方案:ifstream file(filename); 改为 ifstream file(filename.c_str()); string类型不能默认转换为char*