Reno
Reno

Reputation: 1139

How do I check if next word from a file in stream isalpha?

I have a file, InputFile.txt, in the format, firstname, lastname, score:

Mike Smith 80
James Jones 75

I want to read those values into my c++ program using an ifStream&. This is how I am doing it:

std::ifstream inStream("InputFile.txt");

std::string firstname;
std::string lastname;
int score;

while(inStream.peek() != EOF)
{
inStream >> firstname >> lastname >> score;

//further processing ignored for brevity...
}

I want to check whether the firstname and lastname are isalpha() == true and that the score is all digits (probably with isdigit().

The following approach is not working:

    while (inStream >> firstname)
    {
        for (auto element : firstname)
        {
            if (!isalpha(element))
            {
                std::cerr << "Error not a alpha character.";
            }
        }
    }

What is the easiest way to do this?

Upvotes: 0

Views: 155

Answers (1)

jvd
jvd

Reputation: 774

You can directly write

while (inStream >> fname >> lname >> score)
{
    //further processing ignored for brevity...
}

It will evaluate to implicit true if and only if the whole statement is successfully read. I.e., you don't need to verify that the score is a number here. It will be read as a number.

As for the matter of fname and lname, I would suggest a check something along the lines

inline bool is_alpha(const std::string& s) noexcept {
   return std::find_if_not(s.begin(), s.end(),
                           [](unsigned char c) { return std::isalpha(c); }) == s.end();
}

Upvotes: 3

Related Questions