提问者:小点点

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


基于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文件,其中的元素之间用逗号分隔?


共2个答案

匿名用户

你想读数字后跟冒号吗?

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

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 ','
     std::string dummy;
     if (is >> dummy) 
        if (!(dummy.length() == 1) || !(dummy[0]==','))
            is.setstate(std::ios_base::failbit);
     return is;
}

然后在代码中-将double value;替换为number value;

匿名用户

你可以试试这样的东西

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