How to store multiple lines of input?

Viewed 63

I am trying to read multiple lines of input from the user. My code below works fine, but my professor only allow us to use 'break' in switch statements. This is my function below:

void getaddress (char address [ ], int limit)
{

    int len = 0;

   while(fgets(address+len, limit, stdin))
   {
       if(strlen(address+len) == 1)
       break;

       limit = strlen(address);
       limit = limit - len;

       if(limit <= 0)
       break; 
   } 
}
2 Answers

Consider simply reading until no room as the first test of the while() loop.

void getaddress(char address[ ], int limit) {
  int offset = 0;
  while(offset + 1 < limit && fgets(address+offset, limit - offset, stdin)) {
    offset += strlen(address + offset);
  } 
}

If is important that size in fgets(ptr, size, stdin) is at least 2 to avoid problems.

I think

 limit = strlen(address);//error
 len += strlen(address); // correct

See below

void getaddress (char address [ ], int limit)
{

    int len = 0;

   while(fgets(address+len, limit, stdin) && limit > 0)
   {
       switch(address[len]){
case '\0': break;
case '\n':case '\r': continue;
default:;
}

       len += strlen(address);
       limit -= len;
   } 
}
Related