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?
3 Réponses
+ 2
Betina Then instead of applying std::isdigit() and std::isspace(), you can check the ASCII value of the current character.
+ 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
+ 1
Shadow But I have to do it only with for loop and I can’t use any other library except iostream.