Reputation: 77
is there an easier way to write this if statement?
int main ()
{
char k[100];
int i=0;
ifstream fd ("info.txt");
while (!in.eof())
{
fd >> k[i]
if (int(k[i]) != 96 || int(k[i]) != 97 ||
int(k[i]) != 98 || int(k[i]) != 99)
i++;
}
}
and so on till 122. Basically all I want to do is check if the symbol in the .txt file matches all the alphabet letters, @ sign and a " . " (period)
Is there an easier way to do all of this? Any help is much appreciated !
Upvotes: 1
Views: 111
Reputation: 57678
Try this:
char c;
while (fd >> c)
{
if ((c < '`') || (c > 'c'))
{
k[i] = c;
++i;
}
}
Usually, using character constants is more readable than their ASCII decimal equivalents.
Also, using eof in a loop is considered wrong, so place the input operation in the while
expression.
Since your values are contiguous, you can use the <
and >
operators to reduce the number of comparisons.
Edit 1:
Another alternative is to place the valid letters into a string and search the string.
const std::string invalid_letters = "@.abcdefghijklmnopqrstuvwxyz";
while (fd >> c)
{
if (invalid_letters.find(c) == std::string::npos)
{
k[i] = c;
++i;
}
}
You can also use islower
to detect lowercase letters.
Upvotes: 4
Reputation: 6406
int countemailchars(istream & is)
{
char ch;
int answer = 0;
while(is.get(&ch))
{
if(strchr("abcdefghijklmnopqrstuvwxyz.@", tolower(ch)))
answer++;
}
return answer;
}
ifstream fd ("info.txt");
int N = countemailchars(fd);
Upvotes: 0
Reputation: 7321
You can write your if statement like this:
if (int(k[i]) < 96 || int(k[i]) > 122){
i++;
}
Upvotes: 0