简体   繁体   中英

islower function to output boolean value of 0 or 1 depending on input

I tried the following but am not getting 0 or 1. The question is how do I make this program print out a boolean value of 0 or 1 without using conditional statement in C++.

char input;
char output;
cout << "Input A Character: \n";
cin >> input;
input = islower(input);
cout << input;    

To get either 0 or 1 , you can use the double ! operation:

cout << !!input;

!! is a common idiom to normalize boolean values. It yields 0 when the value is 0 and 1 when the value is non- 0 .

Some people don't like the double negation, and you can get the same result with the != equality operator:

cout << (input != 0);

Use an int instead of a char :

int result = islower(input);
cout << result; 

Note that islower is only guaranteed to return "0" or "something that isn't 0". You can fix that by writing cout << (result ? 1 : 0) , but I'm not sure if that is disallowed by your requirements.

islower should return 0 when the character is NOT a lowercase letter.

Remember that only 0 is false . Even if the function returns -1, it's still a true value.

Check out the reference here .

EDIT:

You can try using input = 1 && islower(input); . This will force you true value to become 1.

Both 0 and 1 are non-printable characters, that's why you don't see the output. If you redirect the output to a file and open with a hex editor you'll see the result.

Store the result in a boolean, or cast the result: cout << (bool) input;

Every value except 0 == true. 0 == false.

you can store the output of islower(input) in an integer variable, say value , and cout << value

int value = islower(input);
cout << input;
#include <iostream>

using namespace std;

int 
main() 
{
  char input;
  cout << "Input A Character: \n";
  cin >> input;
  unsigned int bIsLower = islower(input);
  cout << "input: " << input << ", bIsLower: " << bIsLower << endl;    
  return 0;
}

Input A Character:
a
input: a, bIsLower: 2

Input A Character:
A
input: A, bIsLower: 0

Input A Character:
z
input: z, bIsLower: 2

To print a boolean value use a variable of type bool .

   char input;
   bool output;
// ^^^^
   cout << "Input A Character: \n";
   cin >> input;
   output = islower(input);
// ^^^^^^  Store result in a bool variable (otherwise why have output)
   cout << output;   
//         ^^^^^^^  Now print it.

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