Using ifstream to assign default value if it was not declared in .txt file

谁都会走 提交于 2021-01-05 09:00:10

问题


Could you please help in modifying the following code to add two things:

  1. having the ability to assign manual(default) value to a[i] if i was not available in the .txt file (e.g. first line in text file is 0, 0, 40, , 15 the forth element in nothing and in this case I want to assign it manually in the code to be for instance 70).
  2. letting the code read not only numbers but also strings (dealing with numbers and strings for example 0,0,8,"turn_right",4)
    struct Number
    {
       double value;
       operator double() const { return value; }
    };
    std::istream& operator >>(std::istream& is, Number& number)
    {
         is >> number.value;
         // fail istream on anything other than ',' or whitespace
         // end reading on ',' or '\n'
        for (char c = is.get();; c = is.get()) {
            if (c == ',' or c == '\n')
                break;
            if (std::isspace(c))
                continue;
    
            is.setstate(std::ios_base::failbit);
            break;
        }
         return is;
    }
    
    
    //reading from text file
    static std::vector<double> vec;
    double a[18]; //values got read from txt file
    int i=0;
    void readDATA(){
    Number value;
    std::ifstream myFile;
    myFile.open("waypoints_cordinates.txt", std::ios::app);
    if (myFile.is_open()){
        std::cout << "File is open."<<std::endl;
        while(myFile >> value){
            vec.push_back(value);
            std::cout << "value is " <<value<< std::endl;
            a[i]=value;
            std::cout << "a" << i << "=" << a[i] << std::endl;
            i=i+1;
            }
        myFile.close();
    }
    else std::cout << "Unable to open the file";
    }

The .txt file is like following:

0, 0, 40, 45, 15
0, 1, 40, -45, 10
0, 0, 180, 90, 15

来源:https://stackoverflow.com/questions/65275129/using-ifstream-to-assign-default-value-if-it-was-not-declared-in-txt-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!