Only Letters On String

Hi I am new in c++

i would like to ask if how to put only letter on a string

if the user put a number on it the system will say Invalid input..
and if the user put letters on it it will continue
Hello portrap099,

Welcome to the forum.

I through this together quickly to give you an idea of something you could do.

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
#include <iostream>
#include <cctype>

bool CheckString(std::string str)
{
	bool good{ true };

	for (size_t lc = 0; lc < str.length(); lc++)
	{
		if (std::isspace(str[lc]))  // <--- Checks for spaces.
			;
		else if (std::ispunct(str[lc]))  // <--- Checks for punction characters.
			;
		else if (!(std::isalpha(str[lc])))
		{
			std::cout << "Error message" << std::endl;
			std::this_thread::sleep_for(std::chrono::seconds(3));  // Requires header files "chrono" and "thread"
			return false;
		}
	}

	return good;
}

int main()
{
	std::string str{ "This is a string" };
	//std::string str{ "Th1s is a string" };

	if (CheckString(str))
		std::cout << "The string is good" << std::endl;

	return 0;
}


This could likely be shortened, but I did not have the time to work on it. Some of what is in the function is there more for ideas of what can be done.

Hope that helps,

Andy

Edit: See this for more ideas: http://www.cplusplus.com/reference/cctype/
Last edited on
Topic archived. No new replies allowed.