You have two kind of problems:
- a logic related one
- a C++ related one
The logic is:
(1) is alpha string <=> all chars are alpha
the contraposition
(2) is not alpha string <=> it exists at least one non alpha char
hence the code is something like:
For all char c in string
if c is not char return false <--- (2 in action)
End for
return true <--- (1 in action)
You have to choose between C or C++. Please do not use C++ to code like in C.
If you want to learn C++ the site https://en.cppreference.com/w/ is a great source of information.
A possible C++ solution is as follows:
#include <string>
#include <iostream>
bool isAlphaStr(const std::string& to_check)
{
for(auto c:to_check)
if(!std::isalpha(c)) return false;
return true;
}
int main()
{
char string_1[]="Hello world!";
std::string string_2{"Hello"};
std::cout << "\nIs alpha? " << std::boolalpha << isAlphaStr(string_1);
std::cout << "\nIs alpha? " << std::boolalpha << isAlphaStr(string_2);
}
To compare C++ style versus C style I have added a pure C version:
#include <string.h>
#include <ctype.h> // for isalpha
#include <stdio.h>
#include <stdbool.h>
bool isAlphaStr(const char *const to_check)
{
const size_t n = strlen(to_check);
for(size_t i=0;i<n;++i)
if(!isalpha(to_check[i])) return false;
return true;
}
int main()
{
char string_1[]="Hello world!";
char string_2[]="Hello";
printf("\nIs alpha? %d", isAlphaStr(string_1));
printf("\nIs alpha? %d", isAlphaStr(string_2));
}
Regarding to Wyck comment, here is version with the bool alphabetic
variable:
C++:
#include <string>
#include <iostream>
#include <type_traits>
bool isAlphaStr(const std::string& to_check, bool alphabetic)
{
if(to_check.empty()) return alphabetic;
for(auto c:to_check)
if(!std::isalpha(c)) return false;
return true;
}
int main()
{
char string_1[]="Hello world!";
std::string string_2{"Hello"};
std::cout << "\nIs alpha? " << std::boolalpha << isAlphaStr(string_1,false);
std::cout << "\nIs alpha? " << std::boolalpha << isAlphaStr(string_2,false);
}
C:
#include <stdio.h>
#include <stdbool.h>
bool isAlphaStr(const char *const to_check, bool alphabetic)
{
const size_t n = strlen(to_check);
if(!n) return alphabetic; // empty string special case
for(size_t i=0;i<n;++i)
if(!isalpha(to_check[i])) return false;
return true;
}
int main()
{
char string_1[]="Hello world!";
char string_2[]="Hello";
printf("\nIs alpha? %d", isAlphaStr(string_1,false));
printf("\nIs alpha? %d", isAlphaStr(string_2,false));
}