Write a c++ program that calculates a number of spaces in a string using pointers.
Make a separate function that takes a pointer then using for loop it calculates all spaces.
This code has been tested on the c++ Code blocks compiler
This example covers the concept of
- pointers in c++
- functions
- loops in c++
C++ source code
#include <iostream> using namespace std; void Calculate_Spaces_alpha(char *); int main() { char string [] = "This string contains four spaces"; cout <<"String is "<<"\n%----------------------%\n" << string << endl; char *str = string; Calculate_Spaces_alpha(str); return 0; } void Calculate_Spaces_alpha(char *ptr) { int spaces = 0; int characters = 0; for ( ; ; ptr++) { if (*ptr == ' ') spaces++; if (*ptr != '\0') characters++; else break; } cout << "\nIn the String: "<< endl << "Characters: "<< characters << endl <<"Spaces: " << spaces << endl; }
This code has been tested on the c++ Code blocks compiler
also check more examples here: C++ Example Source Codes
0 comments:
Post a Comment