sizeof
gives you the size of the type of the object passed to it. It is evaluated strictly at compile time. You are passing it a const char *
, which is 8
on 64
bit systems.
To get the length of a C
-style string, you can use the C
function strlen
, in the header <cstring>
.
That said, I would recommend not doing this. I would recommend moving away from C
strings to C++
std::string
s, because they are much easier to use correctly.
Now as it is, you are very much using C
strings INcorrectly!
int main() {
char x;
cout << "Enter the string of characters" << endl;
cin >> x;
const char *password = &x;
check(password);
}
You read a single char
(x
), then take its address and treat this as a C
string. Now there are two significant problems here.
First, you probably meant to read more than one character.
Second, you will hit undefined behaviour, and your computer may well blow up, because C
strings are supposed to be a pointer to a NUL
-terminated array of char
. Any functions that expect a C
string will loop through look for an ending '\0'
, which x
does not have, since it is not even an array in the first place.
So, if you use std::string
from the <string>
header, you can have much safer code, without all this faffing with pointers, NUL
-terminators, and such.
(untested)
// one of your functions for example
bool isUpperLetter (const std::string& s){
for(int x=0; x < s.size(); ++x){ // Use <, not <=. C++ uses 0-indexing.
if(isupper(s[x]))
return true;
}
return false; // you forgot this!
}
int main() {
std::string s;
std::cout << "Enter a string:\n";
std::cin >> s;
isUpperLetter(s);
}
By the way, this won't work if your input string contains spaces, but one thing at a time!
(Next steps if you learn fast: Read up on std::getline
and the <algorithm>
header. std::count_if
looks very relevant.)
And while we're at it, kill bad habits early, and read up on why you should avoid using namespace std;
and std::endl
.
EDIT
From your comment, you are stuck with the signature bool check(const char*)
, so I guess you are supposed to be learning about how to work with C
strings. Let's for the moment assume your instructors know what they are doing.
Then the normal way to loop through a C
string is with a pointer, checking for '\0'
. So for instance, to count the number of uppercase letters (and really, you don't write it this way for real code. Or at least, if you tried to on a project I was working on I would strongly suggest you fix it):
int countUppercase (const char* c)
{
if(NULL==c) return 0;
int count = 0;
for ( ; '\0' != *c ; ++c ) // loop while not found the NUL
{
if (isupper(*c))
++count;
}
return count;
}
I still strongly recommend reading into a std::string
if you can get away with it. If not, you're next best bet is probably std::istream::getline
.