isalpha and ispunct work punctiliously, but isspace spaces out.

cout << "Please enter an integer: ";
	cin	 >> str;
	int bogus = 0;
	for (int i = 0; i < str.length(); i++)
	{
		char temp = str.at(i);
		if (isalpha(temp) || isspace(temp) || ispunct(temp))
		{
			cout	<< "Please try again!"	<< endl;
			cout	<< "The bad character is "	<< temp	<< endl;
			bogus++;
			break;
		}
	}
	if (bogus < 1)
		cout	<< "Succeeded with "	<< str	<< endl;

Rich

Dani AI

Generated

A short expert note tying the thread together and adding a few follow-ups.

As and correctly pointed out, the immediate reason isspace appeared to "not work" was input: the extraction operator (operator>>) stops at whitespace, so the string contained no spaces to detect. confirmed that switching input fixed the visible symptom. Beyond that fix, a few robustness points are worth noting.

  • ctype functions (like isspace, isalpha, ispunct) expect an int value either equal to EOF or representable as an unsigned char. Passing a plain char that is negative can cause undefined behavior. Always call the std versions with an explicit cast: std::isspace(static_cast<unsigned char>(ch)) and include <cctype>.
  • These functions classify single-byte characters according to the current C locale. They do not understand UTF-8 codepoints; for Unicode-aware whitespace checks decode to code points or use a Unicode library / wide-character facilities.
  • When mixing operator>> and std::getline, be sure to remove the leftover newline (std::cin.ignore() or handle accordingly) to avoid empty reads.

Example (safe, getline-based check):

#include <iostream>
#include <string>
#include <cctype>

std::string line;
if (std::getline(std::cin, line)) {
    for (char ch : line) {
        unsigned char uch = static_cast<unsigned char>(ch);
        if (std::isalpha(uch) || std::ispunct(uch) || std::isspace(uch)) {
            std::cout << "Bad character: '" << ch << "'\n";
            break;
        }
    }
}

Extra tips: isspace returns an int (nonzero = true), trim any trailing '\r' when reading Windows-style lines, and consider std::use_facet<std::ctype<char>>(locale) or a Unicode library for locale/Unicode-sensitive classification.

Recommended Answers

All 4 Replies

You realize that the >> operator for input is is default delimited on whitespace, right?

> cin >> str;
This won't read a string with spaces - it uses spaces for a delimiter to begin with.

Use getline() to read a whole line - spaces and all, then try.

I knew it, then forgot it. Thanks - it's fixed.

Yup, you're right - I had gotten too used to using cin for everything. Thanks.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.