Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Sorting my file of strings into my vector thinks I am trying to put characters in it?

When trying to use fstream to enter csv data into my program I am having an odd problem using a vector but it works fine with a random-sized array. I am not sure why but the error I am getting from visual studio is that there is no suitable conversion from string to char even though my vector is for strings. I am not sure if this is happening because of some weird case where it is trying to push back something I didn’t intend even though I double-checked it by putting outputs to see where it was happening.

==== Function ====
ifstream dataEve;
dataEve.open(fileName, std::ifstream::in);

std::vector<std::vector<string>> dataStore;
//string dataStore[10][10];                  ***works if you replace the vector above***

string currentLine;
string currentObject;
int x = 0;
int y = 0;

while (!dataEve.eof()) {
    getline(dataEve, currentLine, '\n');
    stringstream ss(currentLine);
    string currentLine;
    while (std::getline(ss, currentObject, ',')) {
        dataStore[x][y].push_back(currentObject);
        //dataStore[x][y] = currentObject;        ***works fine if you use this too***
        std::cout << currentObject << "\t";
        y++;
    }
    x++;
    std::cout << "\n";
}
std::cout << "\n\n";

dataEve.close();

==== fileName.csv ====
Organism,Genetic Code
Felis catus,ACTG
Canis lupis,ATCG

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Like this

dataStore.push_back(std::vector<string>()); // add a new 'row'
while (std::getline(ss, currentObject, ',')) {
    dataStore.back().push_back(currentObject); // push the string onto the last 'row'
    std::cout << currentObject << "\t";
    y++;
}
x++;

As you can see from this code you don’t actually need the x and y variables, but I left them in anyway.

Two errors in your code, firstly dataStore[x][y] doesn’t exist as the vector has zero size, so that would be a run time error.

Secondly dataStore[x][y] is a string, so if you push_back on a string the compiler expects you to give a char. That’s the reason for the compiler error.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading