4

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);
}
user2661167
  • 491
  • 5
  • 13
  • 22
  • 1
    First, you shouldn't need `-std=c++11` for `atoi`. But I'd avoid `atoi`, since it doesn't allow any error checking. A better solution would be `strtoi`. – James Kanze Oct 11 '13 at 08:22
  • And what is this mania for using `stringstream`, when what you want is `istringstream`? (I see it all the time, and I don't understand why anyone would do it.) – James Kanze Oct 11 '13 at 08:23
  • Also, instead of `istringstream`, for this sort of format, I'd use something like `boost::split` (which still leaves the issue of converting to `int` open). – James Kanze Oct 11 '13 at 08:24

2 Answers2

4

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;
}
wangyang
  • 49
  • 1
  • 4
    First, he doesn't have a `char const*`, but an `std::string`. And second, Such functions need a lot more error checking if they are to be useful. – James Kanze Oct 11 '13 at 08:26
2

You are already using stringstream, which gives you such "feature".

void func()
{
    std::string strnum1("1");
    std::string strnum2("2");
    int number1;
    int number2;
    std::stringstream convert;

    convert << strnum1;
    convert >> number1;

    convert.str(""); // clear the stringstream
    convert.clear(); // clear the state flags for another conversion

    convert << strnum2;
    convert >> number2;
}
  • Why be simple when you can be complicated? You don't need (nor necessarily want) bidirectional `stringstream`. Just use `istringstream`, initialized with the correct string. – James Kanze Oct 11 '13 at 08:26