How to extract numbers from a string containing commas? [Solved] | Sololearn: Learn to code for FREE!
0

How to extract numbers from a string containing commas? [Solved]

I'm a beginner, working on all the "easy" Code Coach supplementary exercises. Have finished all but 3, but I'm finding the last ones a little difficult. Here is the given task: " Evaluate the area of two different balconies and determine which one is bigger. Input Format Your inputs are two strings where the measurements for height and width are separated by a comma. The first one represents apartment A, the second represents apartment B. Output Format: A string that says whether apartment A or apartment B has a larger balcony. Sample Input '5,5' '2,10' " I have found ways to extract or alter one char in a string, but how can I extract a number > than a single char (like '10' in the Sample Input of the Task)? I think I can solve the task fairly easily if I can learn how to seperate the whole numbers from the string. Hopefully any suggestions will keep in mind the challenge is at "easy" level and should therefore be resolved using a beginners set of tools.

11th Nov 2022, 6:17 AM
Scott D
Scott D - avatar
3 Answers
+ 3
Two ways but actually only one: 1) Make a dummy char for the comma. int width; int height; char comma; cin >> width >> comma >> height; 2) Some people may recommend something like this: int wdth, hght; scanf("%d,%d", &wdth, &hght); Yes, that works. But that is C not C++. And it is said thou shalt not mix C and C++. It is bad style, and usually done by people who migrate to C++ from C without having really learned C++ but figure, hey, it's basically the same, just add some OOP. -- No, it is not. C++ is a language on its own. And especially when dealing with I/O, it is best not to mix C puts,scanf and C++ cin/cout streams. I am just mentioning this second way as bad example. That is why I said two but only one in the beginning.
11th Nov 2022, 7:17 AM
Ani Jona 🕊
Ani Jona 🕊 - avatar
+ 2
Ani Jona 🕊 Brilliant! Works perfectly. So for the two apartments (just testing the input before processing): int main() { int widthA, heightA, widthB, heightB; char comma; cin >> widthA >> comma >> heightA >> widthB >> comma >> heightB; cout << widthA << ' ' << heightA << ' ' << widthB << ' ' << heightB; So simple but completely effective. Thanks again!
11th Nov 2022, 7:54 AM
Scott D
Scott D - avatar
+ 1
You're welcome again 🙂
11th Nov 2022, 7:54 AM
Ani Jona 🕊
Ani Jona 🕊 - avatar