#dealing with EOF

1 messages · Page 1 of 1 (latest)

maiden smelt
#
   them into dest. Returns the number of characters written into 
   dest, including the terminating null character. The function
   stops copying characters if it encounters the newline character
   ('\n') or EOF (i.e., the line ends) or if lim-1 characters have been
   read (to allow space for a terminating null character). */
int csc225_getline(char dest[], int lim)
{
  int c = EOF;

  int i = 0;
  for (i; i < lim - 1; i++)
  {
    c = getchar();
    if (c == EOF || c == '\n')
      break;

    dest[i] = c;
  }

  if (c == '\n')
  {
    dest[i++] = c;
  }

  dest[i] = '\0';

  return i;
}

int main()
{
   
    char dest[MAX_LINE_LEN];
    char src[MAX_LINE_LEN];
    
    
    csc225_getline(src, MAX_LINE_LEN);
     printf("%s", src);
      csc225_strncpy(dest, src, MAX_LINE_LEN);
    while(1)
    {
        csc225_getline(src, MAX_LINE_LEN);
        if(csc225_strncmp(dest, src, MAX_LINE_LEN) != 0)
        {
            printf("%s", src);
            csc225_strncpy(dest, src, MAX_LINE_LEN);
        }
        
    }
    return 0;
}```
 Anyone got any tips on how I can fix the infinite loop in my main so that my program stops when it enoucounters an EOF or when crtlD is inputted
untold skiffBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For more information use !howto ask.

prime cargo
#

well, you're not using the return value of csc225_getline, are you allowed to modify it to return a bool which you could use to indicate EOF or not?

#

alternatively you could just check for a return value of 0 from csc225_getline, meaning no characters were read

#

(if it was an empty line you would have written \n and returned 1)

maiden smelt
#

Idk where to go after that

prime cargo
#

in your main, check if the function returns 0, if so, then there's nothing more to be read

#
    while(1)
    {
        const int num_chars_read = csc225_getline(src, MAX_LINE_LEN);
        if (num_chars_read == 0) { break; }
        if(csc225_strncmp(dest, src, MAX_LINE_LEN) != 0)
        {
            printf("%s", src);
            csc225_strncpy(dest, src, MAX_LINE_LEN);
        }
    }
maiden smelt
#

Ok imma try that in a sec

maiden smelt
#

i got this error @prime cargo

#

oh wait nvm

#

its cus its outside

maiden smelt
#

@prime cargo IT WORKED!

#

ive been stuck on it for a min thx for the help

maiden smelt
#

!solved

untold skiffBOT
#

Thank you and let us know if you have any more questions!

#

[SOLVED] dealing with EOF