why cant my printf pick up my user input?

前端 未结 2 1983
花落未央
花落未央 2021-01-16 16:42

I have this

void main(int argnum, char** input)
{
   int a=0, b=0, c=0, d=0, e=0, f=0, g=0, h=0, i=0, j=0, k=0, l=0, m=0, n=0, o=0, p=0;

   printf("Ente         


        
相关标签:
2条回答
  • 2021-01-16 17:09

    (separate by comma)

    If you're separating the numbers with commas, the second and subsequent scans will fails, because there's no way to turn a comma into an integer.

    Scanning for an %d integer will:

    • skip white space (which does not include commas); then
    • scan as many characters as needed to populate an integer, up until the first character that's not part of an integer.

    If the first non-whitespace character is a comma, that's not suitable for an integer. Easiest solution is probably just to tell user to separate with spaces rather than commas.


    Let's begin with a cut-down version that exhibits the same behaviour (and with single strings rather than those disparate ones):

    #include <stdio.h>
    
    int main(void) {
        int a=0, b=0;
    
        printf("Enter numbers from 1 to 2 in any order (separate by comma): ");
    
        scanf("%d %d", &a, &b);
        printf("%d %d\n", a, b);
    }
    

    Entering 1,2 for that gives you 1 0 as per your code. Entering 1 2 (space-separated rather than comma) gives you 1 2, which is what you're after.

    Of course, if you need the commas, you can put that into the format string as well:

    scanf("%d ,%d", &a, &b);
    

    This will:

    • %d - skip optional whitespace and read integer;
    • <space>: skip whitespace before comma;
    • ,: skip comma;
    • %d - skip optional whitespace and read integer.

    Of course, it goes without saying that you should always check things that can fail, if that failure can affect you adversely:

    if (scanf("%d %d", &a, &b) != 2) { // expect two things scanned
        fprintf(stderr, "Something went horribly wrong!\n");
        exit(1);
    }
    
    0 讨论(0)
  • 2021-01-16 17:12
    #include<stdio.h>
    void main(int argnum, char** input)
    {
       int a=0, b=0, c=0, d=0, e=0, f=0, g=0, h=0, i=0, j=0, k=0, l=0, m=0, n=0, o=0, p=0;
    
       printf("Enter the numbers from 1 to 16, in any order(separate by comma) : ");
    
       scanf("%d" "%d" "%d" "%d" "%d" "%d" "%d" "%d" "%d" "%d" "%d" "%d" "%d" "%d" "%d" "%d", &a, &b, &c, &d, &e, &f, &g, &h, &i, &j, &k, &l, &m, &n, &o, &p);
       printf("%d " "%d " "%d " "%d \n", a, b, c, d);
       printf("%d " "%d " "%d " "%d \n", e, f, g, h);
       printf("%d " "%d " "%d " "%d \n", i, j, k, l);
       printf("%d " "%d " "%d " "%d \n", m, n, o, p); 
      
    } 
    

    after taking each value from the keyboard please press enter button it will work with this code

    0 讨论(0)
提交回复
热议问题