使用 ifstream 读取带逗号的 .txt 文件

Using ifstream to read .txt file with comma

基于 ifstream 我正在使用以下函数读取 filename.txt 文件

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

它工作正常 以下是 filename.txt 文件的内容:

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

能否请你帮我修改函数,这样我就可以读取同一个 .txt 文件,元素之间用逗号分隔

您想阅读数字后跟冒号吗?

定义将处理此“任务”的 class:

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

然后在您的代码中 - 将 double value; 替换为 Number value;

Demo

类似这样的你可以试试

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