0

it has to be a non-negative int no larger than 23....no blank entries or other entries, if so it reprompts the user again I have

int main(void){
int rows;


while (rows < 1 || rows > 23)
{
printf("Height:");
scanf("%d", &rows);
}

then idk what to do for the other.

is it NULL? orrrr what lol how would I implement that

  • 1
    Undefined behavior. `rows` is uninitialized and might contain 18 if unlucky. – Basile Starynkevitch Jan 19 '14 at 19:59
  • Note that 0 is a non-negative integer; your code, though, rejects it as invalid. If you mean 'positive integer', use that term. If you mean 0 is valid, fix the comparison. As it is, the problem specification is ambiguous between the code and the verbiage. – Jonathan Leffler Jan 19 '14 at 20:41

1 Answers1

1

Avoid undefined behavior by initializing rows (its undefined initial garbage value could be 18 if you are unlucky)....

Read an entire line using getline(3) or else fgets(3).

Then parse that line using sscanf(3) (take into account the result of sscanf and perhaps use %n) or using strtol(3) (e.g. long n=strtol(p,0,&end); after declaring char *end=NULL;)

See this and that answers.

Or at least, use the result of scanf like

int rows = 0;
while(1) {
 puts("number of rows?");
 fflush(stdout);
 int nbscan = scanf("%d", &rows);
 if (nbscan<=0) continue;
 if (rows < 1 || rows>20) continue;
 if (feof(stdin)) break;
}
Community
  • 1
  • 1
Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547