c++ - Cannot get ispunct or isspace to work, but isupper works fine. Can you help me? -


this code outputs number of capital letters. outputs nummarks , numspaces 0. i've tried sentence.c_str() same results. cannot understand what's happening.

cout << "please enter sentence using grammatically correct formatting." << endl; string sentence = getline(); int numspaces = 0; int nummarks = 0; int numcaps = 0; char words[sentence.length()]; for(int = 0; < sentence.length(); ++i) {     words[i] = sentence[i];     if(isspace(words[i]) == true)     {         numspaces++;     }     else if(ispunct(words[i]) == true)     {         nummarks++;     }     else if(isupper(words[i]) == true)     {         numcaps++;     } } cout << "\nnumber of spaces: " << numspaces; cout << "\nnumber of punctuation marks: " << nummarks; cout << "\nnumber of capital letters: " << numcaps; 

edit: fixed problem. compiler weird. had remove == true , worked perfectly. information though. know future

the functions isspace, ispunct, isupper using have return type int. return 0 if not match, , non-zero if match. don't return 1, testing == true may fail though check succeeded.

change code be:

if ( isspace(words[i]) )   // no == true 

and should start working (so long don't type extended characters - see below).


further info: there 2 different isupper functions in c++ (and same other 2 functions). are:

#include <cctype> int isupper(int ch) 

and

#include <locale> template< class chart > bool isupper( chart ch, const locale& loc ); 

you using first one, legacy function coming c. using incorrectly passing char; argument must in range of unsigned char. related question.

so fix code properly, choose 1 of following 2 options (including right header):

 if ( isupper( static_cast<unsigned char>(words[i]) ) ) 

or

if ( isupper( words[i], locale() ) ) 

other things: char words[sentence.length()]; illegal in standard c++; array dimensions must known @ compile-time. compiler implementing extension.

however redundant, write sentence[i] , not use words @ all.


Comments

Popular posts from this blog

java - Spring Data JPA: Why findOne(id) executing delete query internally? -

python - Mongodb How to add addtional information when aggregating? -

java - Incorrect order of records in M-M relationship in hibernate -