Search code examples
c++stringstreamistringstream

Assigning variables from configuration file to int16_t variables in c++


I have use stringstream to parse the configuration file. The c++ integer variables are working fine while assigning the values from the text file.However, when I assign the read value from configuration file to c++ int16_t variables, it just assigns a different value. I donot know what is going on.

This is my code:

void parseConfigurationFile(){
  //Variables
  int16_t int16_tValue;
  int firstIntegerValue;

  //File parsing code
  std::ifstream fin(configFileName);
  std::string line;
  std::istringstream sin;

  while (std::getline(fin, line)) 
  {
   sin.str(line.substr(line.find(":")+1));
   if (line.find("firstIntegerValue") != std::string::npos) {
       sin >> firstIntegerValue;
   }  
   else if (line.find("int16_tValue") != std::string::npos) {
       sin>>int16_tValue;
   }  
}

My configuration file looks like follows :

firstIntegerValue : 12
int16_tValue : 55555

What might be possibly going wrong here? I could not figure this out.


Solution

  • Your input, 55555, is beyond the range of int16_t. Since int16_t is a signed quantity, there is one bit reserved for the sign, so you have less positive range. You are overflowing a signed 16-bit integer.

    Your value may be interpreted as a negative number.

    You may want to enter a smaller value or use uint16_t.