Preview:
#include <iostream>
#include <string>

int countWords(std::string str) {
    int wordCount = 0;
    bool inWord = false;

    for (char ch : str) {
        if (ch != ' ') {  // Если символ не пробел
            if (!inWord) {  // Если мы не находимся в слове
                wordCount++; // Начинаем новое слово
                inWord = true; // Мы теперь внутри слова
            }
        } else {  // Если символ пробел
            inWord = false; // Выходим из слова
        }
    }

    return wordCount; // Возвращаем количество слов
}

int main() {
    std::string input;
    std::cout << "Введите строку: ";
    std::getline(std::cin, input);  // Чтение строки с пробелами

    int wordCount = countWords(input);
    std::cout << "Количество слов в строке: " << wordCount << std::endl;

    return 0;
}
downloadDownload PNG downloadDownload JPEG downloadDownload SVG

Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!

Click to optimize width for Twitter