Why is C ++ reading values ​​from txt files incorrectly?

I created a program that reads a value from the txt file "database.txt", but the output is incorrect when the number is three digits

ifstream myfile("database.txt"); int broj_rijeci = 0; if (myfile.is_open()) { while (getline(myfile, line)) { if (line.at(0) == '[') { int i = line.length() - 2; int brojac = 0; system("pause"); while (line.at(i) != line.at(0)) { input = line.at(i); ascii_convert(input); broj_rijeci = broj_rijeci + input * pow(10, brojac); i--; brojac++; } } } myfile.close(); } else cout << "Unable to open file"; 

and my database is as follows:

 [311] 

pin 310

+6
source share
2 answers

Since you did not provide an ascii_convert implementation, it is difficult to determine if there is a problem there or somewhere else. However, you can greatly simplify the process and eliminate the need for your own conversion procedures with std::stringstream .

 #include <sstream> std::ifstream myfile("database.txt"); if (myfile.is_open()) { std::string line; while (std::getline(myfile, line)) { if (line.size() > 1 && line[0] == '[' && line[line.size() - 1] == ']') { int value; if(std::istringstream(line.substr(1, line.size() - 2)) >> value) { // Conversion was a success ... do something with "value" } else { // Conversion failed. Handle error condition. } } } myfile.close(); } else std::cout << "Unable to open file"; 
+3
source

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"; } } } 
0
source

All Articles