C++ Programming
- Write a C++ Program to print a welcome text in a separate line.
- Write a Program in C++ to add two numbers.
- C++ program for addition of two numbers using functions.
- Add two numbers in C++ using class.
- Addition of two numbers using call by reference in C++
- C++ program to write a program to add two numbers using call by value.
- Swapping of two numbers in C++ without using third variable.
- Swap two numbers in C++ using function.
- C++ program to swap two numbers using class.
- C++ program to swap two numbers using call by value.
- C++ program to swap two numbers using pointers.
- Write a program to swap private data members of two classes using friend function.
- write a program to add data objects of two different classes using friend function.
- Threading in C++.
- C++ thread lambda
- C++ thread lambda with parameter
- C++ thread lambda pass by reference
- Singleton C++ example
Write a C++ program to count all the characters, blank spaces and words in a given string.
Method 1
#include <iostream>
#include <string>
using namespace std;
int main() {
string str;
//Give the initials
int characterCount = 0, wordCount = 0, blankSpaceCount = 0;
cout << "Enter any sequence of words or line: ";
getline(cin, str);
for (char c : str) {
characterCount++;
if (c == ' ') {
blankSpaceCount++;
}
}
//Words should be separated by single space
wordCount = blankSpaceCount + 1;
cout << "Number of characters: " << characterCount << endl;
cout << "Number of words: " << wordCount << endl;
cout << "Number of blank spaces: " << blankSpaceCount << endl;
return 0;
}
Output
Enter any sequence of words or line: Coddesire is for programming and technology
Number of characters: 43
Number of words: 6
Number of blank spaces: 5
Method 2
#include <iostream>
#include <string>
using namespace std;
//Function to count character words and space
void count(const std::string& input, int& charCount, int& wordCount, int& spaceCount) {
bool inWord = false;
for (char ch : input) {
//Words should be separated by a single space
if (ch != ' ') {
charCount++;
if (!inWord) {
wordCount++;
inWord = true;
}
} else {
spaceCount++;
inWord = false;
}
}
}
int main() {
string input;
cout << "Enter any sequence of words or line: ";
getline(cin, input);
//Give the initials
int charCount = 0, wordCount = 0, spaceCount = 0;
count(input, charCount, wordCount, spaceCount);
cout << "Number of characters : " << charCount <<endl;
cout << "Number of words: " << wordCount <<endl;
cout << "Number of spaces: " << spaceCount <<endl;
return 0;
}
Output
Enter any sequence of words or line: CodDesire is for programming and technology
Number of characters : 38
Number of words: 6
Number of spaces: 5