Ask coding questions

← Back to all posts
Any ideas on how I can fix this?
Wolfclaw1226 (0)

Yeah, So, I didn't expect this bug to happen. Just check out the note on my program. P.S. this is in C++

Answered by Coder100 (16985) [earned 5 cycles]
View Answer
Comments
hotnewtop
Coder100 (16985)

C++ implicitly coerces non-number things into numbers, namely the number 0.

Cool!

Instead use stoi which is allowed to throw errors

#include <iostream>
#include <string>
 
int main() {
    std::string s;
    std::getline(std::cin, s);
 
    try {
        int balance = std::stoi(s);
        // TODO: DO THOSE COMPARISON CHECKS
    }
    catch (std::invalid_argument const &e) {
        std::cout << "Bruh that ain't a number what are you thinking" << std::endl;
    }
    catch (std::out_of_range const &e) {
        std::cout << "Hey Mr. Rich you are too rich" << std::endl;
    }
 
    return 0;
}

also stap using namespace std that's dumb and bad practice

SixBeeps (5056)

@Coder100 there's a bug in your code, if you underflow the number it says you're rich even though you're $2147483648 in debt

RohilPatel (1534)

Hey, so std::cin basically only takes in one character. At least that's how I like to think of this. Now I have a solution, although it's not really the most practical.

#include <iostream>
#include <fstream>
#include <string>

int main () {
  std::string textAsString;
  std::getline(std::cin, textAsString);
  
  int x = std::stoi(textAsString);

 if (x == 50) std::cout << "hi" << std::endl;
  return 0;
}
Coder100 (16985)

hey why are you not responding

SixBeeps (5056)

I'm not an expert in C++, but what I think is happening is either the values in the char array (which are stored as a byte, as any other data type) or the pointer to the char array are being interpreted as a double byte, and it's then comparing it to the 400.00. Either that or somehow trying to store a string defaults to 0.0.

I'm actually curious as to what this is doing as well, if someone could ping me with an actual solution that'd be great.

Coder100 (16985)

yeah, it implicitly converts the string into the number 0.
std::cin isn't allowed to throw errors i don't think @SixBeeps