0

I'm new to c, and I'm not sure how to word this question. But for example using this code:

#include <stdio.h>

int main()
{
    int x,y,z;

    printf("Enter 2 numbers: ");
    scanf("%d %d", &x, &y);

    printf("Test: ");
    scanf("%d",&z);

    printf("x:%d y:%d z:%d\n",x,y,z);

    return 0;
}

If the user inputs "1 2 3", it would set x=1, y=2 and z=3. I was wondering if you could set x=1 and y=2 and ignore 3, then the user can input another value and not use the 3 given before.

TechnoCA
  • 1
  • 1
  • 6
    You can flush the input after the first scanf. [See here](http://stackoverflow.com/questions/7898215/how-to-clear-input-buffer-in-c). – M.M Oct 09 '16 at 02:56
  • 5
    You can use [`fgets()`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/fgets.html) (or POSIX [`getline()`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/getline.html)) to read a line and then scan it with [`sscanf()`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/sscanf.html) instead of `scanf()`. This is often a better way to process data; it allows you to report errors better, and allows you to try alternative ways of scanning the data if the first format doesn't work. – Jonathan Leffler Oct 09 '16 at 03:01
  • 1
    Totally agree with @JonathanLeffler: You should use `fgets()` to get one line, then `sscanf()` to process it carefully (checking the return values from those functions, of course). – John Zwinck Oct 09 '16 at 03:05
  • Well you may want to use scanf("%d",&z); scanf("%d",&z); that is, scan the value two times. The first one will be overwritten This is not the obvious solution but it may help – Anish Sharma Oct 10 '16 at 09:42

1 Answers1

0

This code will help you:

#include <stdio.h>
#include <stdlib.h>

int main() {
    int x,y,z;
    char s[1024];

    printf("Enter 2 numbers: ");
    scanf("%d %d", &x, &y);
    fgets(s, 1024, stdin);

    printf("Test: ");
    scanf("%d",&z);

    printf("x:%d y:%d z:%d\n",x,y,z);

    return 0;
}

It initializes a string pointer with 1024 bytes and after reading the first two integers ignore the remaining content on that line, then prompts Test: and reads z variable.

EDIT Use code below as I tested it with line of 0 <= lentgh <= 8.1k characaters!

#include <stdio.h>
#include <stdlib.h>

int main() {
    int x,y,z;
    char ch;

    printf("Enter 2 numbers: ");
    scanf("%d %d", &x, &y);
    while(scanf("%c", &ch)) if(ch == '\n') break;

    printf("Test: ");
    scanf("%d",&z);

    printf("x:%d y:%d z:%d\n",x,y,z);

    return 0;
}
Masked Man
  • 2,176
  • 2
  • 22
  • 41