2

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; 
   } 
}
Fred
  • 240
  • 2
  • 9
  • 1
    `if (address[len] == '\n') goto done;` then after the `}` of the loop `done:;`. (checking for `'\n'` catches **Enter** alone as input for `fgets()`) If you are checking for some other condition with `strlen(address+len) == 1`, then you can use that instead. – David C. Rankin Oct 03 '20 at 03:54
  • 1
    `while (limit > 0 && fgets(…) != NULL) { … }`, taking care not to destroy `limit` as you currently do. Your loop body needs to calculate the new limit differently. – Jonathan Leffler Oct 03 '20 at 03:57
  • 1
    It appears `limit = strlen(address);` should be `len = strlen(address);` -- otherwise what `limit` was -- is changing each iteration `:)` – David C. Rankin Oct 03 '20 at 03:59
  • @DavidC.Rankin you are right!!! – Fred Oct 03 '20 at 04:00
  • 1
    Combine that with the limits to your read to protect your `limit` @chux shows in his answer and you will have a solid routine. – David C. Rankin Oct 03 '20 at 04:07
  • 1
    Joana F., is the buffer size was 100, and with 3 input lines of length 40,40,40, should the last line get partially saved, lost or what? – chux - Reinstate Monica Oct 03 '20 at 04:09
  • @chux-ReinstateMonica the max size is 80, so what is left should be lost and maybe throw an error to retype again. – Fred Oct 03 '20 at 04:12
  • 1
    Joana F. My answer will need adjustment to handle this new requirement. Simple look for a `fgets()` result that lacks a `'\n'` in the data just read. See `strchr()`. – chux - Reinstate Monica Oct 03 '20 at 04:15
  • @chux-ReinstateMonica your code is working perfectly fine! Thanks a lot – Fred Oct 03 '20 at 04:18

2 Answers2

2

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.

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
1

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;
   } 
}