0
Balconies Example C++ need help
Hello, i‘m just starting c++ and have fun with the code coach practices. Right now i#m trying to solve Balconies but i just dont get the string with to numbers devided by „ , „ into any variable type i can calculate with. i know that there are some examples online for getting. numbers out of a string but in my point of view the are not related to the level „easy“ Very thankfull for any hint!
3 Antworten
+ 3
You can convert a string to an integer by the std::stoi() function:
https://en.cppreference.com/w/cpp/string/basic_string/stol
The function skips any potential whitespace and then takes as many characters as possible to form a valid number. This means the first number can be obtained through a simple call on the string:
int height = std::stoi( s ); // string s
However, the second call needs to start at the comma, and since you don't know beforehand where that is, you have to search for it through a call to find():
https://en.cppreference.com/w/cpp/string/basic_string/find
std::stoi() doesn't give you the option not to begin at the start, but the substr() method allows you to construct a string starting at a given position. Since the second number starts after the comma, we need to start parsing at the index of the comma incremented by one. The whole call to get the second number thus looks like this:
int width = std::stoi( s.substr( s.find( ',' ) + 1 ) );
You can then repeat this for the second input.
0
thx for quick response. i have read about this online. i just wonder that this should be part of a practice wich is arked as easy so i thought there must be a solution with simpler methods...
0
It definitely becomes easier with higher-level languages such as Python or Ruby, which have functions implemented for exactly this purpose, yes. You'll have to do a bit more by yourself in C++.