I tried to read a console input by executing C++-style
int main()
{
std::string str;
std::getline(std::cin, str);
// also tested: std::cin >> str;
return 0;
}
and C-style
int main()
{
char* str = new char[20];
scanf_s("%s", str);
delete[] str;
return 0;
}
But if I enter a string and press enter, the cursor in console won't jump to the next line, it jumps to the first column of the line where the entered command is located. A second key down on enter will cause an error:
Error message box after executing C++-style code:
Debug Assertion Failed! Program: D:\_extern\Test\Test.exe File: minkernel\crts\ucrt\src\appcrt\lowio\read.cpp Line: 259 Expression: static_cast<void const*>(source_buffer) == static_cast<void const*>(result_buffer) For information on how your program can cause an assertion failure, see the Visual C++ documentation on asserts.
Error after executing C-style code:
Exception triggered at 0x00007FF95C9398E9 (ucrtbased.dll) in Test.exe: 0xC0000005: Access violation when writing at position 0x0000019155DF1000.
What could be the problem?
You're not calling scanf_s()
correctly, you're calling it as if it were ordinary scanf()
. From the documentation:
Unlike
scanf
andwscanf
,scanf_s
andwscanf_s
require the buffer size to be specified for all input parameters of typec
,C
,s
,S
, or string control sets that are enclosed in[]
. The buffer size in characters is passed as an additional parameter immediately following the pointer to the buffer or variable. For example, if you are reading a string, the buffer size for that string is passed as follows:char s[10]; scanf_s("%9s", s, (unsigned)_countof(s)); // buffer size is 10, width specification is 9
So in your case, you need to write:
scanf_s("%s", str, 20);
User contributions licensed under CC BY-SA 3.0