Bryan Wong
Bryan Wong

Reputation: 633

Convert vector<string> * char to int

I need help in my following code and hope that you can help me through. All I wanted is to pass in INT type to setX() and setY(). However, there is no way for me to convert vector char* to int. Is there alternative to this?

template<class T>
vector<string> Delimiter(T inputString){
    int count=0;
    char str[inputString.length()];
    strcpy(str,inputString.c_str());
    char * pch;

    vector<string> returnContainer;

    printf ("Splitting string \"%s\" into tokens:\n",str);
    pch = strtok (str,",[]");
    while (pch != NULL)
    {
        returnContainer.push_back(pch);
        pch = strtok (NULL, " ,[]");
        count++;
    }
    for(int i=0; i<returnContainer.size(); i++){
    cout << "return:" << returnContainer[i] << endl;
    }
    return returnContainer;
}

//Main()

fileDataAfterFiltered = Delimiter(fileData[i]); // Delimiter (vector<string> type)

point2DObj[point2DCount].setX(fileDataAfterFiltered[1]); // error
point2DObj[point2DCount].setY(fileDataAfterFiltered[2]); // error

//Assn3.cpp:107:59: error: no matching function for call to ‘Point2D::setX(std::basic_string&)’

Upvotes: 1

Views: 2161

Answers (3)

Tom Tanner
Tom Tanner

Reputation: 9354

there's plenty of ways of converting string to int. boost::lexical_cast is one which will magically do the conversion you want. Otherwise you can use atoi (if you don't care about errors), or strtol (if you do).

point2DObj[point2DCount].setX(atoi(fileDataAfterFiltered[1].c_str()));
point2DObj[point2DCount].setX(boost::lexical_cast<int>(fileDataAfterFiltered[1]));

Upvotes: 1

Olaf Dietsche
Olaf Dietsche

Reputation: 74018

Delimiter() returns a vector<string> and you give one of these strings to setX() and setY(), but both expect an integer parameter. You must convert the string to int

int x = atoi(fileDataAfterFiltered[1].c_str());
point2DObj[point2DCount].setX(x);
int y = atoi(fileDataAfterFiltered[2].c_str());
point2DObj[point2DCount].setY(y);

But: in C++ array and vector elements start at 0 not 1, so you might want to replace this with fileDataAfterFiltered[0] and fileDataAfterFiltered[1] respectively.

Upvotes: 1

Gorpik
Gorpik

Reputation: 11028

If you are using a C++11 compiler, function std::stoi() will do the trick:

point2DObj[point2DCount].setX(std::stoi(fileDataAfterFiltered[1]));

Otherwise you can use the old atoi():

point2DObj[point2DCount].setX(atoi(fileDataAfterFiltered[1].c_str()));

Aside from this, your code has many other problems, but I hope you can fix them by yourself.

Upvotes: 1

Related Questions