控制台未正确读取输入字符串

Console not reading input string correctly

本文关键字:输入 字符串 读取 控制台      更新时间:2023-10-16

我试图通过执行C++式来读取控制台输入

int main()
{
std::string str;
std::getline(std::cin, str);
// also tested: std::cin >> str;
return 0;
}

和 C 型

int main()
{
char* str = new char[20];
scanf_s("%s", str);
delete[] str;
return 0;
}

但是,如果我输入一个字符串并按 Enter 键,控制台中的光标不会跳到下一行,它会跳到输入命令所在的行的第一列。在回车时按下第二个键将导致错误:

执行C++式代码后的错误消息框:

Debug Assertion Failed!
Program: D:_externTestTest.exe
File: minkernelcrtsucrtsrcappcrtlowioread.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.

执行 C 样式代码后出错:

Exception triggered at 0x00007FF95C9398E9 (ucrtbased.dll) in Test.exe: 0xC0000005: Access violation when writing at position 0x0000019155DF1000.

可能有什么问题?

你没有正确调用scanf_s(),你把它当作普通scanf()来调用它。从文档中:

scanfwscanf不同,scanf_swscanf_s要求为所有类型为cCsS或字符串控制[]集的输入参数指定缓冲区大小。以字符为单位的缓冲区大小作为附加参数传递,紧跟在指向缓冲区或变量的指针之后。例如,如果您正在读取一个字符串,则该字符串的缓冲区大小将按如下方式传递:

char s[10];
scanf_s("%9s", s, (unsigned)_countof(s)); // buffer size is 10, width specification is 9

所以在你的情况下,你需要写:

scanf_s("%s", str, 20);