M
M
Murad Murtuzaliev2020-05-23 14:48:51
C++ / C#
Murad Murtuzaliev, 2020-05-23 14:48:51

Why doesn't comparison with space character work?

I'm trying to display the number of occurrences of a space in a string, but for some reason the comparison of the string character and the space character does not give a result.

#include <iostream>
#include <string>

int main() {
    int counter = 0;
    std::string input;
    std::cin >> input;
    for (int i = 0; i < input.size(); i++) {
        if (input[i] == ' ')
            counter += 1;
    }
    counter += 1;
    std::cout << counter << std::endl;
}


simple string
1

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
maaGames, 2020-05-23
@ordinary_programmer

cin reads characters up to the first whitespace, read with cin.getline.

U
User700, 2020-05-23
@User700

Or you can try to disable skipping spaces
std::cin.unsetf(ios::skipws);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question