Write a C++ code to count the number of characters, words, and lines entered by the user. The program stops if the user enters two dots.

User Icon for Explain Bot Explain Bot answered
1 year ago

Sure! I can help you write a C++ program that counts the number of characters, words, and lines entered by the user. Here's an example code:

```cpp
#include <iostream>
#include <string>

int main() {
std::string input;
int charCount = 0;
int wordCount = 0;
int lineCount = 0;

std::cout << "Enter text (two dots to stop):" << std::endl;

// Read input line by line
while (getline(std::cin, input)) {
// Check if the user entered two dots to stop
if (input == "..")
break;

// Count characters
charCount += input.size();

// Count words
bool inWord = false;
for (char c : input) {
if (c == ' ' || c == '\t' || c == '\n')
inWord = false;
else if (!inWord) {
inWord = true;
wordCount++;
}
}

// Count lines
lineCount++;
}

std::cout << "Character count: " << charCount << std::endl;
std::cout << "Word count: " << wordCount << std::endl;
std::cout << "Line count: " << lineCount << std::endl;

return 0;
}
```

Explanation:
1. We start by including necessary header files: `iostream` for input/output operations and `string` for string manipulation.
2. In the `main()` function, we declare variables to track the number of characters, words, and lines. Initialize each count to zero.
3. Prompt the user to enter text (terminate with two dots) using `std::cout`.
4. We then use a `while` loop to read user input line by line using `getline()`.
5. Inside the loop, we check if the user entered two dots in a line to stop. If so, we break out of the loop.
6. To count the number of characters, we increment `charCount` by the size of the current input line using `input.size()`.
7. To count the number of words, we iterate over each character in the input line using a `for` loop. If a character is a space, tab, or newline, we set `inWord` to false. If a character is not a space, tab, or newline and `inWord` is false, we set `inWord` to true and increment `wordCount` by 1.
8. To count the number of lines, we simply increment `lineCount` by 1 for each line inputted by the user.
9. Finally, we print the accumulated counts of characters, words, and lines using `std::cout`.

That's it! You now have a C++ program that counts the number of characters, words, and lines entered by the user, stopping when two dots are entered.