Replacing your code will be SSCCE showing the expected result:
#include <iostream> #include <sstream> #include <string> #include <math.h> int main() { std::istringstream myfile("[311]"); int broj_rijeci = 0; for (std::string line; std::getline(myfile, line); ) { if (2 < line.size() && line.at(0) == '[') { int i = line.length() - 2; int brojac = 0; while (line[i] != line[0]) { char input = line[i]; input -= '0'; broj_rijeci = broj_rijeci + input * pow(10, brojac); i--; brojac++; } } } std::cout << "result=" << broj_rijeci << '\n'; }
However, this code is probably much slower than necessary. For example, calculating the power of even an integer performs a couple operations at each iteration, while only one multiplication is required:
#include <iostream> #include <sstream> int main() { std::istringstream in("[311]"); for (std::string line; std::getline(in, line); ) { if (2 < line.size() && line.front() == '[' && line.back() == ']') { int result(0); for (std::string::const_iterator it(line.begin() + 1), end(line.end()); std::isdigit(static_cast<unsigned char>(*it)); ++it) { result = result * 10 + *it - '0'; } std::cout << "result=" << result << '\n'; } else { std::cout << "ERROR: unexpected format on line '" << line << "'\n"; } } }
source share