控制台未正确读取输入字符串
Console not reading input string correctly
我试图通过执行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()
来调用它。从文档中:
与
scanf
和wscanf
不同,scanf_s
和wscanf_s
要求为所有类型为c
、C
、s
、S
或字符串控制[]
集的输入参数指定缓冲区大小。以字符为单位的缓冲区大小作为附加参数传递,紧跟在指向缓冲区或变量的指针之后。例如,如果您正在读取一个字符串,则该字符串的缓冲区大小将按如下方式传递:char s[10]; scanf_s("%9s", s, (unsigned)_countof(s)); // buffer size is 10, width specification is 9
所以在你的情况下,你需要写:
scanf_s("%s", str, 20);
相关文章:
- C++,在int数组中输入字符串或字符会输出0,而不是ascii或error
- 用户输入字符串的文件附加问题..C++
- 从 cin 读取不会返回整个输入字符串
- 输出返回编号。等于输入字符串的单词的字符串数
- 控制台未正确读取输入字符串
- 使用终止程序的指针在数组中输入字符串
- 如何删除用户输入字符串末尾的空字符?
- 在循环中使用 cin.get() 输入字符串
- 如何从输入字符串中提取特定位置的字符?
- 用户输入字符串的结构的搜索向量
- 无法使用 getline() 输入字符串.它只读取一个字符串
- 如何在 c++ 中读取输入字符串,忽略空格
- FSTREAM的问题读取确定,但不编写用户输入字符串
- boost::split会在输入字符串不是常量时更改输入字符串吗?
- 通过键盘输入字符串数组和 int 数组的数组大小
- Zlib 放气输入大于原始输入字符串的字符
- C 忽略输入字符串
- 获取一个输入字符串,将其转换为其十六进制值,然后将其十六进制存储为 int
- 我无法将 Excel 中的输入字符串存储为二维字符串
- 如何识别输入的输入字符串在 c++ 中是两个还是多个单词