Search code examples
c++type-conversionintcharacter

Imprecision when passing from string to int character by character in c++


First of all I am taking the string from geline(cin, s) and the input is in the form of: 100 49. And I can not take it with normal cin because I need to know where geline(cin, s) makes s empty so that means is a blank line and I should stop the program. When passing from string '99' (or any other number below 100) to int 99 there is no problem. But when I try a number greater than 99 it gave the (number - 1). Also I found that this happens with numbers below 1000 but from 1000 to 10000 it is ok, but I tested number greater than 10^4 and it gave the (number - 1) another time. Here is my code to convert the string

//Search how many nums are in the string wer are passing until an space or new line

int nums = 0;

for(int j = i; j < s.size(); j++){
  if(s[j] == ' ' || s[j] == '\n') break;
  nums++;
 }

 //pass to the variable time the string character by character
 int time = 0;

 while(nums--){
    time += (s[i] - '0') * (pow(10, nums));
    i++;
}

I would like to know if there is an error from my computer or I am missing something.


Solution

  • First of all I am taking the string from geline(cin, s) and the input is in the form of: 100 49.

    Then simplest solution is to use std::istringstream:

    int i1 = 0, i2 = 0;
    std::istringstream( s ) >> i1 >> i2;