Home > Back-end >  'scanf_s' function doesn't work well in my C project
'scanf_s' function doesn't work well in my C project

Time:12-23

My code:

#include <stdio.h>
int main() {
    char words[30];

    printf("Please typing text under 30 text!:");
    scanf_s("%s", words);

    printf("text: %s \n", words);

    return 0;
}

The error I get:

Missing integer argument to 'scanf_s' that corresponds to coversion specifier '2', 'scanf_s' not enough arguments passed for format string

CodePudding user response:

Consider using fgets instead if you're simply reading everything into a string buffer. It's simpler and more portable:

char buffer[31]; // 1 extra for the zero terminator

printf("Please enter text with less than %zu characters\n", sizeof(buffer) - 1);

if (!fgets(buffer, (int)sizeof(buffer), stdin)) {
  puts("Failed to read input");
} else {
  // use input
}

CodePudding user response:

As you can see in the scanf_s documentation:

specifiers each expect two arguments (the usual pointer and a value of type rsize_t indicating the size of the receiving array, which may be 1 when reading with a %c into a single char)

I.e. for each argument you want scanf_s to parse, you need to pass its size.

Also scanf family return the number of arguments parsed, and you should check it to find out if it actually succeeded.

In your case change the scanf_s line to:

int n = scanf_s("%s", words, sizeof(words));
if (n != 1)
{
    // handle error
}

Note that sizeof(words) works here because it is an array allocated on the stack. If you allocate it as a pointer with malloc family you'll need to pass the right size (because then sizeof will return the size of the pointer itself).

CodePudding user response:

Try this code:

#include <stdio.h>

    int main() {
      char words[30];
    
      printf("Please typing text under 30 text!:");
      scanf_s("%s", words,30);
    
      printf("text: %s \n", words);
    
      return 0;
    }

Also, you could put sizeof(words) instead of 30 as someone suggsted. (Note that this is only possible if you are working with static memory)

If you are using scan_s I think you want to ensure to read n symbols. Someone already suggested you to use fgets. Another possible solution is to use memcpy (you will read the exact bytes):

#include <stdio.h>

    int main() {
      char words[30];
      char words2[30];

    
      printf("Please typing text under 30 text!:");
      scanf("%s", words);
      memcpy(words2,words,sizeof(char)*30);
      words2[sizeof(char)*30]='\0';
      printf("text: %s \n", words2);
    
      return 0;
    }
  •  Tags:  
  • c
  • Related