Saturday, May 22, 2010

Write a C++ program that reads a string and print the number of digits, number of space, number of upper case?

thx 4 helping :)

Write a C++ program that reads a string and print the number of digits, number of space, number of upper case?
The previous reply didn't answer the exact question you asked, but did show you what to do. My code below does what you're asking for. The character counting is pretty basic stuff, so I thought I'd toss in some C++ tricks to make it interesting, and help you learn something.





One nice thing about setting up the code this way is that if your want to count a different set of characters, you don't have to do anything to the code in main( ).





#include %26lt;string%26gt;


#include %26lt;iostream%26gt;


#include %26lt;cctype%26gt;





using namespace std;





struct Counts {


int digit;


int space;


int upper;


Counts() {


digit = space = upper = 0;


}


void count(const string%26amp; s) {


for (string::const_iterator i = s.begin(); i != s.end(); i++) {


if (isdigit(*i)) ++digit;


else if (isspace(*i)) ++space;


else if (isupper(*i)) ++upper;


}


}


};





ostream%26amp; operator%26lt;%26lt;(ostream%26amp; os, const Counts%26amp; c) {


os %26lt;%26lt; ". digit = " %26lt;%26lt; c.digit %26lt;%26lt; endl;


os %26lt;%26lt; ". space = " %26lt;%26lt; c.space %26lt;%26lt; endl;


os %26lt;%26lt; ". upper = " %26lt;%26lt; c.upper %26lt;%26lt; endl;


return os;


}





int main(int argc, char *argv[]) {


string str;


struct Counts cnt;





cout %26lt;%26lt; "Enter string: ";


getline(cin,str);


cnt.count(str);


cout %26lt;%26lt; "Counts:" %26lt;%26lt; endl %26lt;%26lt; cnt;


return 0;


}
Reply:#include %26lt;iostream%26gt;


#include %26lt;string%26gt;


#include %26lt;cctype%26gt;


using namespace std;


int main()


{


string text;


cout %26lt;%26lt; "Please enter the text and terminate with a period(.) and press enter:\n";


getline( cin, text, '.');


int t,


numberOfSpace = 0,


numberOfWords = 0;





bool fSpace = true;


for( t = 0; t %26lt; text.length(); ++t)


{


if( isspace( text[t]) )


{


++numberOfSpace;


fSpace = true;


}


else if( fSpace)


{


++numberOfWords;


fSpace = false;


}


}


cout %26lt;%26lt; "\nYour text contains: "


%26lt;%26lt; "\ncharacters: " %26lt;%26lt; text.length()


%26lt;%26lt; "\nwords: " %26lt;%26lt; numberOfWords


%26lt;%26lt; "\nspaces: " %26lt;%26lt; numberOfSpace


%26lt;%26lt; endl;





system("PAUSE");


return EXIT_SUCCESS;


}

magnolia

No comments:

Post a Comment