CSTRING PROBLEM WITH SCANF_S

Write your question here.
Why doesn't scanf_s work for strings? When I print cstr, cstr is blank.

1
2
3
4
5
6
7
8
9
10
11
  #include <cstdio>


int main(void)
{
	char cstr[16];
	printf_s("String please: ");
	scanf_s("%15s", cstr);
	printf_s("Thanks for the %s!\n", cstr);
}
Wait, is this C or C++?

If it's C, then change the #include <cstdio> to #include <stdio.h> .
If it's C++, then prefer std::string, std::cout, and std::cin over char[], printf, and scanf.

In any case, does this work?
scanf_s("%15s", cstr, _countof(cstr));
long double main,

Thank you for your response. I am taking a free online course in C but am programming in C++. I am fully aware there are differences.

I have come to the conclusion that scanf_s in C++ does not work with string, char, or char*.
I have come to the conclusion that scanf_s in C++ does not work with string, char, or char*.

Your conclusion should be that you don't understand how to use scanf_s. Fortunately, you don't need to.

You should steer clear of scanf_s in both C and C++ if you want your code to be portable as it is a nonstandard function ("optional" in C11) that, in practice, is only available on MS compilers.

As long double main notes, the number of elements in the array must be fed to scanf_s in the argument list immediately after the pointer to it.
cire,

When I wrote that statement, I tried almost every combination possible, including what long double main said. Now that I am a little wiser, yes, my statement should have been that I don't understand how to use scanf_s.

The function does work if you include the header <cstdlib> and the _countof(cstr).
Topic archived. No new replies allowed.