Scanf_s在 C++ 中为空
Scanf_s is empty in c++
我不能使用此代码,因为我不会编写任何文本。如何通过阅读解决这个问题?
#include "stdafx.h"
#include "stdio.h"
#include "conio.h"
#include "string.h"
int _tmain(int argc, _TCHAR* argv[])
{
char str[1024];
printf("Input text: ");
scanf_s("%c", str);
_asm
{
//some assembly code
}
printf("nnResult = %s", str);
printf("nn[Press any key]");
_getch();
return 0;
}
结果是
Input text: sdf
Result =
[Press any key]
有什么想法吗?我使用Visual Studio 2013。
我不知道函数
scanf_s
,所以我查找了文档。它指出,为了scanf
scanf_s
缓冲区大小,需要为格式说明符指定c
、C
、s
和S
作为通常参数之后的第二个参数。举个例子:
char str[1024];
printf("Input text: ");
scanf_s("%s", str, 1024);
该文档还指出,在潜在的缓冲区溢出的情况下,不会向缓冲区写入任何内容。
中的%c
格式说明符
scanf_s("%c", str);
请求读取单个char
。
printf("nnResult = %s", str);
稍后请求打印str
的内容,直到第一个值为 ' '
的char
。 这会导致未定义的行为,因为您只初始化了str
的第一个元素。 您有时可能会设法打印一系列堆栈内存;其他时候,您的程序会崩溃。
假设你想读取一个以 nul 结尾的字符数组,你需要在读取用户输入时使用%s
格式说明符:
scanf_s("%s", str);
按如下方式使用。
scanf("%[0-9a-zA-Z ]s", str);
%c 只会从输入值中读取一个字符。
%s 将读取一个单词(直到空格)
扫描 %s
Any number of non-whitespace characters, stopping at the first whitespace character found. A terminating null character is automatically added at the end of the stored sequence.
<</div>
div class="answers"> 我遇到了同样的问题,我收集了几个答案,我让用户用空格和数字写下他的名字,谢谢!
"#include "stdafx.h"
"#include < iostream >"
"#include < stdio.h >"
"#include < locale.h >"
using namespace std;
int main()
{
setlocale(LC_ALL, "spanish");
char a [100];
printf_s("n Programa para la práctica de scanf_s ");
printf_s("n Introduzca su nombre completo: ");
scanf_s("%[0-9a-zA-Z ]s", &a, 100);
printf_s("n ¡Bienvenido! Sr. %s", a);
cout << " n This is a white spacen "<<a;
system("PAUSE()");
return 0;
}
相关文章:
- scanf() 只取数字作为输入,避免使用其他字符
- 为什么我的 scanf() 没有在我的数组上迭代我的 for 循环?
- 当我尝试使用它时,Scanf 会抛出一个随机异常(scanf_s 也是如此)
- 如何通过 scanf() 读取没有标点符号的字符串?
- 为什么这个scanf()的两个不同的输入会给出两个不同的输出?
- C++ - scanf() 和 printf() 执行顺序不对
- scanf( "%d" , array[i] + 1)是什么意思?为什么+1在那里?
- SCANF 读取错误,因为使用 %d 读取布尔值
- 为什么 printf 在 C++ 中的执行速度比 cout 快?另外scanf比cin慢,为什么?
- scanf() 的宽度说明符 - 要使用的字符长度在编译时不固定,仅在运行时确定.如何使其可变?
- 如何在循环中使用scanf,将值存储到一个变量中,然后打印出来?
- scanf() 语句中"%*[^n]"的格式字符串指示什么?分配抑制器 (*) 和否定扫描集 ([^) 如何协同工作?
- 在C/C++中检查数字是否为整数(不带scanf/gets/etc)
- 为什么我应该在scanf()-家族成员中包含一个长度修饰符作为参数?有什么好处?使用长度修改器进行扫描的作用
- 在printf和scanf中%lli和%lld之间的区别?
- 不能使用嵌套结构中的联合元素作为 scanf() 的参数来存储所需的值
- 使用 scanf 读取文件中的图形时出现问题
- 使用 scanf() 具有不同数据类型的多个输入
- 有没有办法中止 cin 或 scanf
- 字母 'f' 在 printf()、scanf() 和 seekg() 中的 'g' 代表什么?