Reputation: 37
I can't use this code because I can't write any text. How can i solve this problem with reading?
#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("\n\nResult = %s", str);
printf("\n\n[Press any key]");
_getch();
return 0;
}
result is
Input text: sdf
Result =
[Press any key]
any ideas? I use Visual Studio 2013.
Upvotes: 1
Views: 5151
Reputation: 1
I had the same problem, I gathered several answers and I got the user to write his name with spaces and numbers, Thanks!
"#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 space\n "<<a;
system("PAUSE()");
return 0;
}
Upvotes: 0
Reputation: 4738
Use as below..
scanf("%[0-9a-zA-Z ]s", str);
%c will only read one char from input value.
%s will read one word (till whitespaces)
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.
Upvotes: 0
Reputation:
I didn't know the function scanf_s
, so I looked up the documentation. It notes, that in constrast to scanf
for scanf_s
buffer sizes need to be specified for format specifiers c
, C
, s
and S
as a second parameter following the usual one. An example:
char str[1024];
printf("Input text: ");
scanf_s("%s", str, 1024);
The documentation also states that in case of potential buffer overflow nothing is written to the buffer.
Upvotes: 4
Reputation: 42165
The %c
format specifier in
scanf_s("%c", str);
requests that a single char
is read.
printf("\n\nResult = %s", str);
later requests that the contents of str
until the first char
with value '\0'
are printed. This results in undefined behaviour since you only initialised the first element of str
. You may sometimes manage to print a range of stack memory; other times your program will crash.
Assuming you want to read a nul-terminated array of chars, you need to use the %s
format specifier when reading user input instead:
scanf_s("%s", str);
Upvotes: 2