Mohamed Bensaleh
Mohamed Bensaleh

Reputation: 21

How to exit C program using Enter key

I'm trying to figure out a way to exit my program by pressing the Enter key when the program asks for a number.

I tried this if statement within my main() but it does not seem to work.

int main()
{
  while(1){
    int val;
    printf("\nnumber to convert:\n ");
    scanf("%i", &val);

    ibits(val);
    if (val = '\n')
    {
      break;
    }
  }

  return 0;
}

Upvotes: 2

Views: 996

Answers (1)

Myst
Myst

Reputation: 19221

You really shouldn't use scanf directly... especially if you're expecting multiple possible formats.

Consider using fread instead and then converting the input to the proper format.

i.e.:

int main() {
  while (1) {
    char buf[1024];
    printf("\nnumber to convert:\n ");
    unsigned long len = fread(buf, 1, 1023, stdin);
    buf[len] = 0;
    if (len == 0 || (len == 1 && buf[0] == '\n') ||
        (len == 2 && buf[0] == '\r' && buf[1] == '\n'))
      break;
    int val = atoi(buf);
    ibits(val);
  }
  return 0;
}

This will also allow you to validate input and test for overflow attacks:

int main() {
  while (1) {
    char buf[1024];
    printf("\nnumber to convert:\n ");
    unsigned long len = fread(buf, 1, 1023, stdin);
    buf[len] = 0;
    if (len > 11)
      goto under_attack;
    if (len == 0 || (len == 1 && buf[0] == '\n') ||
        (len == 2 && buf[0] == '\r' && buf[1] == '\n'))
      break;
    if (buf[0] != '-' && (buf[0] < '0' || buf[0] > '9'))
      goto under_attack;
    int val = atoi(buf);
    ibits(val);
  }
  return 0;

under_attack:
  fprintf(stderr, "Under attack?!\n");
  return -1;
}

Upvotes: 3

Related Questions