开发者

Summing triplets in C

开发者 https://www.devze.com 2023-02-09 23:32 出处:网络
Okay so I have a file with a bunch of digits 002003005\\n 001001\\n and I want to sum all the digits by three so the first lines sum would be 10 and the second line would be 2. Right now I\'m not s

Okay so I have a file with a bunch of digits

002003005\n
001001\n

and I want to sum all the digits by three so the first lines sum would be 10 and the second line would be 2. Right now I'm not sure whats wrong with my control flow

#define MAXLINE 1000
int counter = 0;
int inputLine[MAXLINE] = {0};
int main(void)
{
  int sum = 0;
  int i = 0;
  int ii = 0;
  char c;
  while ((c = getchar()) != EOF)
  {开发者_运维百科
    if (c == '\n')
    {
      for (ii = 0; ii < counter; ii = ii + 3)
      {
        sum = sum + ((inputLine[ii] - '0') * 100) + ((inputLine[ii+1] - '0') * 10) + ((inputLine[ii+2] - '0') * 1);
      }
      printf("%d\n", sum);
      sum = 0;
      counter = 0;
    }

    inputLine[i] = c;
    i++;
    counter++;
  }


  return 0;
}


You're not resetting i when you reach the end of a line.

Insert:

i = 0;

After the counter = 0 line.

You also need to include this block:

inputLine[i] = c;
i++;
counter++;

Within an else, since it shouldn't happen for the carriage return at the end of each line.

Once you've done that, you'll (hopefully) notice that i and counter will always contain the same value on each pass through the loop, so there's no need for them both to exist.


If your char type is unsigned by default then your end condition is not good

char c;
while ((c = getchar()) != EOF)

You should declare c as int, as EOF cannot be represented in the value range of 0..255. EOF is by definition a negative integer of type int used to indicate end-of-file conditions.

0

精彩评论

暂无评论...
验证码 换一张
取 消