简体   繁体   中英

the isupper(), islower(), toupper(), tolower() functions not working in c++

I have a code fragment something like this:

char choice;
do
{
    cout << "A. Option 1" << endl;
    cout << "B. Option 1" << endl;
    cout << "C. Option 1" << endl;
    cout << "D. Option 1" << endl;
    cout << "Option: ";
    cin >> choice;
    if(islower(choice) == 0){ toupper(choice); } // for converting Lower alphabets to Upper alphabets so as to provide flexibility to the user
}while((choice != 'A') && (choice != 'B') && (choice != 'C') && (choice != 'D'));

but it does not converts the Lower alphabets to Upper alphabets... I don't know why... The OS I am using is Windows 7 and the Compiler is Visual C++(please note that I have tested this code in other compilers to but the same problem)...

You should use the returned value, toupper takes a character by value (not reference) and returns the upper case result:

choice = toupper(choice);
^^^^^^^^

Also, the condition should be inverted:

if (islower(choice)) // not: if(islower(choice) == 0)

Use this code, toupper itself checks if the character is lower case or not:

cin >> choice;
choice = toupper(choice);

This line of code

if(islower(choice) == 0){ toupper(choice); }

should be re-write as below,

if(islower(choice)){ choice = toupper(choice); }

The function,

int toupper ( int c );

Return Value The uppercase equivalent to c, if such value exists, or c (unchanged) otherwise. The value is returned as an int value that can be implicitly casted to char.

toupper

islower and isupper tells whether character is upper case or lower case or not.

toupper or tolower does not convert. It takes int parameter and returns an int which is converted character.

To convert use the following:

  choice = toupper(choice);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM