Counting numbers before a space in c++ (please help) | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Counting numbers before a space in c++ (please help)

Hello, I have to count the numbers before the first space in the input of a program. I have no idea how to do that. ex. Input: !@153$ %7 Output: 3 Any ideas how to do it?

14th Mar 2020, 6:43 PM
Betina
Betina - avatar
3 Answers
+ 2
Betina Then instead of applying std::isdigit() and std::isspace(), you can check the ASCII value of the current character.
14th Mar 2020, 7:41 PM
Shadow
Shadow - avatar
+ 1
Get the string, either through std::cin, which automatically stops reading at the first space it encounters, or std::getline(), in case you need to prove that you actually read in the whole string: https://en.cppreference.com/w/cpp/string/basic_string/getline Then just iterate over the string and increment a counter variable whenever you encounter a number, which you can identify via the built-in std::isdigit() function: https://en.cppreference.com/w/c/string/byte/isdigit Or break from the loop if the current character is a space: https://en.cppreference.com/w/c/string/byte/isspace For a more "high-level" solution you could combine std::count_if() and std::find(), but that might be harder if you have not so much experience with C++ and its iterators: https://en.cppreference.com/w/cpp/algorithm/count https://en.cppreference.com/w/cpp/algorithm/find
14th Mar 2020, 7:34 PM
Shadow
Shadow - avatar
+ 1
Shadow But I have to do it only with for loop and I can’t use any other library except iostream.
14th Mar 2020, 7:39 PM
Betina
Betina - avatar