I suggest splitting up the user input part from the checking part.
You could also use the standard library function std::all_of to check that all characters in the string fulfills the requirements.
Example:
#include <algorithm> // std::all_of
#include <cctype> // std::isalpha
#include <iostream>
#include <stdexcept> // std::runtime_error
#include <string>
// the testing part
bool alphabeticString(const std::string& word) {
return
std::all_of(word.begin(),
word.end(),
[](char ch) { // a lambda function for testing a char
return std::isalpha(static_cast<unsigned char>(ch));
}
);
}
// the input part
std::string prompt() {
std::string word;
while(std::cout << "Enter a word: " &&
std::cin >> word &&
not alphabeticString(word))
{
std::cout << "A character is not alphabetical, please try again.\n";
}
// cin is a bad state - extraction of a string failed
if(not std::cin) throw std::runtime_error("utter failure");
return word;
}
int main() {
try {
std::string word = prompt();
std::cout << "You wrote: " << word << '\n';
} catch(const std::exception& ex) {
std::cerr << "Exception: " << ex.what() << std::endl;
}
}
i = -1;.