1

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 !

StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458
TheEnthusiast
  • 77
  • 1
  • 8

3 Answers3

4

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.

Community
  • 1
  • 1
Thomas Matthews
  • 56,849
  • 17
  • 98
  • 154
  • 1
    Character constants are usually more *portable* than codepoints, too. Although that's not the case here, because something is assumed about their ordering... – Toby Speight Oct 10 '16 at 17:01
0

You can write your if statement like this:

    if (int(k[i]) < 96 || int(k[i]) > 122){
        i++;
    }
SpiralDev
  • 7,011
  • 5
  • 28
  • 42
0
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);
Malcolm McLean
  • 6,258
  • 1
  • 17
  • 18