Problems STL string.substring and strtoint

I have this part in my code where i want to make a substring of a string into an int with my str to int function.
I have functioning code. I am wondering why it wont work another way. This is a curiosity question hopefully giving me more insight into this language.
I want to know why one way works and one way doesn't.

Here is my str to Int Function.
1
2
3
4
int aAUtility::strToInt(string &toChange)
{
    return atoi (toChange.c_str());
}



This CODE WORKS
1
2
3
4
5
6
7
8
9
10
int mInt;
string tempstr;
vector<string> myFile;
for (unsigned int i=0; i < myFile.size(); i++)
    {
        for (unsigned int j=0; j < myFile[i].size(); j++)
        { 
            tempstr = myFile[i].substr(j+1);                
            mInt = nwUtil.strToInt(tempstr);
    }   }

____________________________________________________________________________
How come the CODE BELOW does not work? the myFile.substring returns a string but it says there is no matching function call.
Does it have anything to do with me passing my string to strtoint in by reference& ?

Please Explain if you can.

1
2
3
4
5
6
7
8
int mInt;
vector<string> myFile;
for (unsigned int i=0; i < myFile.size(); i++)
    {
        for (unsigned int j=0; j < myFile[i].size(); j++)
        {               
            mInt = nwUtil.strToInt(myFile[i].substr(j+1));
    }   }


Thankyou in Advance.
DoubleA
strToInt takes a non-constant reference as a parameter and you can bind temporaries (the one returned by substr) only to const references.
Since intToStr does not modify the parameter, it should have been const in the first place.
That totally makes sense but unfortunately even after i changed to code to below. It didnt work. Anyone else have any ideas. Or maybe i have done things wrong.
my brain is fried at this point i think ill get some ice cream.

This change still does not work.
1
2
3
4
int aAUtility::strToInt(const string toChange)
{
    return atoi (toChange.c_str());
}
You accidentally removed the & when doing the change.
It should be const string&.

Regardless, that still should have "worked", so perhaps you should elaborate.
Athar You have been a great help. Thankyou for explaining that to me. Your solution did work. i am just so brainfried that i was working on the same code in a different file that was not connected to my current project. I just have too many things open at once. HAH o was getting irritated that your solution wouldnt work because it sounded so elegantly simple and understandable.
One Again Thankyou
Changing to Const worked like a charm
only 2 words added and everything works.

Have a good night i am going to rest my brain.
DoubleA
Last edited on
Topic archived. No new replies allowed.