How do I properly 'printf' an integer and a string in C?

后端 未结 3 929
遥遥无期
遥遥无期 2021-01-03 19:30

I have the following code:

char *s1, *s2;
char str[10];

printf(\"Type a string: \");
scanf(\"%s\", str);

s1 = &str[0];
s2 = &str[2];

printf(\"%s\\         


        
3条回答
  •  梦毁少年i
    2021-01-03 19:57

    You're on the right track. Here's a corrected version:

    char str[10];
    int n;
    
    printf("type a string: ");
    scanf("%s %d", str, &n);
    
    printf("%s\n", str);
    printf("%d\n", n);
    

    Let's talk through the changes:

    1. allocate an int (n) to store your number in
    2. tell scanf to read in first a string and then a number (%d means number, as you already knew from your printf

    That's pretty much all there is to it. Your code is a little bit dangerous, still, because any user input that's longer than 9 characters will overflow str and start trampling your stack.

提交回复
热议问题