Help With Program To Identify Lower Case Strings

Hello everyone,

Beginner C++ student here, first ever programming class. I am trying to put together a program that will identify if a string is all lower case or not. I got as far as the code below. However, I need to account for spaces " ". If there is a space in the string that is input by the user, the program is suppose to return that it is not all lower case. Example:

input: abc def
return: The string is not lower case.

Would any of you ever so kindly advise what would be the best way to account for this in the code below?

NOTE: I know I have 'included' some extra header files, but that is because this is going to be part of another program and this is just an excerpt to get things running.

Thank you so very much all!!


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include <fstream>
#include <iostream>
#include <string>
#include <cstdlib>
#include <algorithm>
#include <cctype>
#include <iomanip>

using namespace std;

bool die(const string & msg);


bool allLower(const string & l);

int main() {

	string l;

	cout << "\nEnter a string (all lower case?): ";
	cin >> l;

	if (allLower(l) == true)
	{
		cout << "The string is lower case." << endl;
	}
	else
	{
		cout << "The string is not lower case." << endl;
	}



}



bool allLower(const string & l) {

	struct IsUpper {
		bool operator()(int value) {
			return ::isupper((unsigned char)value);
		}
	};

	return std::find_if(l.begin(), l.end(), IsUpper()) == l.end();

}

bool die(const string & msg){
	cout << "Fatal error: " << msg << endl;
	exit(EXIT_FAILURE);
}
How about using std::all_of()? It's found in <algorithm>, and it returns true if the condition is true for all elements in the range, false otherwise. Something like this:

1
2
3
std::string string = "abc def";//not a valid string because it has a space

bool valid = std::all_of(string.begin(), string.end(), ::islower);


What's nice about this is that it will account for whitespace characters implicitly, since they aren't considered to be upper- or lowercase characters.
Last edited on
cin >> l; you should change this to getline because the >> operator doesn't input spaces.



1
2
3
4
5
6
7
8
9
10
11
12
13
bool allLower(const string & l)
{
    if(l.find(' ') != std::string::npos)
        return false;

    for(auto element : l)
    {
        if(isupper(element))
            return false;
    }

    return true;
}
Topic archived. No new replies allowed.