Search code examples
c++c++11parsingstdstringistringstream

C++ Determining empty cells from reading in data


I'm reading in data from a csv file that has some columns ending before others, i.e.:

0.01 0.02 0.01
0.02      0.02

And I'm trying to figure out how to catch these empty locations and what to do with them. My current code looks like this:

#include <iostream>
#include <fstream>
#include <sstream>
int main(){

//Code that reads in the data, determines number of rows & columns

//Set up array the size of all the cells (including empty):
double *ary = new double[cols*rows]; //Array of pointers
double var;
std::string s;
int i = 0, j = 0;

while(getline(data,line))
{
    std::istringstream iss(line);    //Each line in a string
    while(iss >> var)                //Send cell data to placeholder
    {
        ary[i*cols+j] = var;
        j+=1;
    }
    i+=1;
}

How can I determine if the cell is empty? I want to convert these to "NaN" somehow. Thank you!


Solution

  • You can do something like follows. Get the inputs, line by line and using (std::getline(sstr, word, ' ')) you can set the deliminator to ' ' and the rest is checking weather the scanned word is empty or not.

    If it's empty, we will set it to NaN(only once).

    Input:
    0.01 0.02 0.01
    0.02      0.02
    0.04      0.08
    

    Here is the output: enter image description here

    #include <iostream>
    #include <fstream>
    #include <sstream>
    #include <vector>
    
    int main()
    {
        std::fstream file("myfile.txt");
        std::vector<std::string> vec;
    
        if(file.is_open())
        {
            std::string line;
            bool Skip = true;
    
            while(std::getline(file, line))
            {
                std::stringstream sstr(line);
                std::string word;
    
                while (std::getline(sstr, word, ' '))
                {
                    if(!word.empty())
                        vec.emplace_back(word);
    
                    else if(word.empty() && Skip)
                    {
                        vec.emplace_back("NaN");
                        Skip = false;
                    }
                }
                Skip = true;
            }
            file.close();
        }
    
        for(size_t i = 0; i < vec.size(); ++i)
        {
            std::cout << vec[i] << " ";
            if((i+1)%3 ==0) std::cout << std::endl;
        }
        return 0;
    }