0

i have a problem with this few lines of code. It works fine in any other compiler than Visual Studio.

int i = 0; 
    char* func[20];
    char com[15];
    while (true)
    {
        scanf_s("%s", com);
        //printf("%s\n", com);
        if (com == "ACTUAL\0")
            cout << "TE\n";
        i++;
    }  

I try to scan a word to char variable ( i have to use chars, cant use string in this exercise ). Im getting this error: (in english it means :Access violation while saving to location )

[1]: https://i.stack.imgur.com/ltb5v.png

But everything works fine in other compilers. I get mad because i'm looking at posts about scan strings into char and it looks very similar to my code. (Sorry if i should tag C instead C++)

NathanOliver
  • 171,901
  • 28
  • 288
  • 402
Kawson
  • 138
  • 1
  • 10

1 Answers1

2

When you use scanf_s to read a %s format specifier, you also have to pass the length of the buffer. That's the key difference between scanf and scanf_s.

scanf_s("%s", com, (unsigned)_countof(com));

That's if you even want to use scanf family functions at all. I'd prefer fgets because it's simpler to read the input first then later parse it (with sscanf or similar)

Govind Parmar
  • 20,656
  • 7
  • 53
  • 85
  • Oh, Thaks a lot. It works fine now. I will look at fgets. Does it read string to variable? (like scanf "%s")? – Kawson Mar 24 '21 at 19:41
  • 1
    @Kawson https://stackoverflow.com/a/1694042/1773434 – Govind Parmar Mar 24 '21 at 19:42
  • 3
    @Kawson - Govind Parmer is correct. You *MUST* specify buffer size as your final argument. Example (https://en.cppreference.com/w/c/io/fscanf): `int n = sscanf_s(input, "%d%f%s", &i, &x, str1, (rsize_t)sizeof str1);`. ALSO: you CANNOT use "==" to compare strings. Use [strcmp()](https://en.cppreference.com/w/c/string/byte/strcmp) instead. FINALLY: you should *ALWAYS* check the return value from scanf/scanf_s. – paulsm4 Mar 24 '21 at 19:44