玻玻麗娜 2022-12-21 10:32 采纳率: 0%
浏览 12

c++ stringstream存檔問題

c++ stringstream不同長度存檔問題
此輸入是一個名稱配上不同長度的長寬,但每行長度不同造成無法存取
input:

BB0 9.11 11.08
MM2 1.9 4.74
MM3 1.9 4.74
MM4 1.9 18.96 2.93 9.48 4.99 4.74
MM5 1.9 18.96 2.93 9.48 4.99 4.74
MM6 1.9 8.48 2.93 4.24
MM7 1.9 8.48 2.93 4.24
MM8 1.9 8.48 2.93 4.24
MM9 1.9 8.48 2.93 4.24
MM10 1.9 55.4 2.93 27.7 11.17 5.54 6.02 11.08
MM11 1.9 11.08 2.93 5.54

code:
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <iostream>
//#include <bits/stdc++.h>
#include <fstream>
#include <errno.h>
using namespace std;
struct Device
{
    string name;
    float weight;
    float height;
    };

void main(){
    vector<struct Device> device_vec;
    Device device_struct; 
    string name;
    //reading file
    //----------------------------------------------
    ifstream inputdevice;
    inputdevice.open("Case0.device",ios_base::in);
    if (!inputdevice.is_open()) { 
        //printf("Error: %s", strerror(errno) );
        cout << "input file opening failed ";
        exit(1); // 程式錯誤終止
    }
    stringstream ss("");
    std::string temp;
    while (getline(inputdevice, temp))
    {        
        ss << temp;
        ss >> device_struct.name >> device_struct.weight >> device_struct.height;
        device_struct = { device_struct.name ,device_struct.weight ,device_struct.height };
        device_vec.push_back(device_struct);
        ss.clear();
        ss.str("");
    }; 
    inputdevice.close();
};
运行结果及详细报错内容

img

我的解答思路和尝试过的方法,不写自己思路的,回答率下降 60%

此'方式只能存到第三個數值,請問該如何解決,謝謝

  • 写回答

3条回答 默认 最新

  • 於黾 2022-12-21 10:59
    关注

    你要么别用循环,每一行到底多长你事先知道,直接写死代码
    否则你必须搞清楚规则是什么,然后用if来判断
    没有规则,别说机器会出错,人也看不懂啊

    评论 编辑记录

报告相同问题?

问题事件

  • 修改了问题 12月21日
  • 创建了问题 12月21日