Scanf_s在 C++ 中为空

Scanf_s is empty in c++

本文关键字:C++ Scanf      更新时间:2023-10-16

我不能使用此代码,因为我不会编写任何文本。如何通过阅读解决这个问题?

#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缓冲区大小,需要为格式说明符指定cCsS作为通常参数之后的第二个参数。举个例子:

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;
}
相关文章: