C++ string to int without using atoi() or stoi()

user2661167 picture user2661167 · Oct 11, 2013 · Viewed 30.2k times · Source

Hi I am new to C++ and trying to do an assignment where we read a lot of data from a txt file in the format of

 surname,initial,number1,number2

I asked for help before an someone suggested reading the 2 values as string then use stoi() or atoi() to convert to int. This works great, except I need to use this parameter "-std=c++11" for compiling or it will return an error. This is not a problem on my own computer which will handle "-std=c++11", but unfortunately for me the machines which I have to present my program on does not have this option.

If there another way which I can convert string to int that doesn't use stoi or atoi?

Here is my code so far.

while (getline(inputFile, line))
{
    stringstream linestream(line);

    getline(linestream, Surname, ',');
    getline(linestream, Initial, ',');
    getline(linestream, strnum1, ',');
    getline(linestream, strnum2, ',');
    number1 = stoi(strnum1);
    number2 = stoi(strnum2);

    dosomethingwith(Surname, Initial, number1, number2);
}

Answer

wangyang picture wangyang · Oct 11, 2013

I think you can write your own stoi function. here is my code, I have tested it, it's very simple.

long stoi(const char *s)
{
    long i;
    i = 0;
    while(*s >= '0' && *s <= '9')
    {
        i = i * 10 + (*s - '0');
        s++;
    }
    return i;
}