坝离梵天 2016-08-13 00:56 采纳率: 0%
浏览 2065
已采纳

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

  • 写回答

8条回答 默认 最新

  • donggua209 2016-08-13 03:32
    关注

    首先,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;
    

    }

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(7条)

报告相同问题?

悬赏问题

  • ¥15 arduino控制ps2手柄一直报错
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥85 maple软件,solve求反函数,出现rootof怎么办?
  • ¥15 求chat4.0解答一道线性规划题,用lingo编程运行,第一问要求写出数学模型和lingo语言编程模型,第二问第三问解答就行,我的ddl要到了谁来求了
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题
  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题