问题
Could you please help in modifying the following code to add two things:
- having the ability to assign manual(default) value to
a[i]
ifi
was not available in the.txt
file (e.g. first line in text file is0, 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). - 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