Convert char to int

Hi, i'm trying to make an exercise for University that receive 2 strings from a file, convert them into separate integers to insert them on stacks(this is said on the statement of the exercise),and using another stack, adds each of the numbers and push the result to the stack. However, i don't know how to make that variable change, any suggestions?

The function is usually called atoi(string toParse, int &retval, int baseValue) or similar. I don't know from the instructions if you are expected to write your own version or not, but you can find instructions on geeksforgeeks pretty easily.

Actually they give several options where you don't have to write your own atoi: https://www.geeksforgeeks.org/converting-strings-numbers-cc/
Last edited on
Why not just use stream extraction to extract direct the numbers from file? What's the format of the file?
One use-case might be parsing g-code. The commands and their values are combined, like this line "G1 X11.37 Y34.096 Z0.05 S1000", the language is modular, so the length, order, and number of descriptors on the line are often different, the next line might be "Y35.5 Z0.07" and that's a legal instruction. If you wanted to test the command parameters virtually before driving it on a $80,000 piece of kit controlled by an ancient computer (or a raspberry pi in some cases), then parsing and converting from string to double is going to be useful.
Though you could get inventive with peek, seekg, tellg, etc., getting it all into ram first and then parsing it out is more efficient, especially when dealing with larger cnc files... (if preferred, the parsing from there could also be done with stringstream if there's enough ram). It's a bit of a niche issue in general, but I don't think it's a bad skill to have for when the weird stuff pops out of the woodwork.

If you need to reverse the process (building a gcode file), then std::to_string found in <string> is overloaded for int and double/float types
Last edited on
Topic archived. No new replies allowed.