简体   繁体   中英

Using ifstream to read .txt file with comma

Based on ifstream I am using the following function to read filename.txt file

//reading from text file
static std::vector<double> vec;
double a[18]; //values got read from txt file
int i = 0;
void readDATA()
{
    double value;
    std::ifstream myFile;
    myFile.open("filename.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";
}

it works correctly Below is the content of filename.txt file:

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

Could you please help me in modifying the function such that I can read the same.txt file with comma separation between the elements?

You want to read number followed optionally by colon?

Define class that will handle this "task":

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

Then in your code - replace double value; with Number value;

Demo

something like this you can try

std::string data;
while(std::getline(myFile, data)) {
    std::istringstream ss(data);
    std::string token;

    while(std::getline(ss, token, ','))
        double d = std::stod(token);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM