How to get string from input in C language - c

This is what i have try:
printf("Please venter first string\n");
char str[127];
scanf_s("%s", &str);
And got this exception:
Exception thrown at 0x0FD2C700 (ucrtbased.dll) in strcmp.exe:
0xC0000005: Access violation writing location 0x00500000.
I also try this:
printf("Please venter first string\n");
char str[127];
scanf_s("%d", &str);
In this case no exception but i got long and strange string.

Let's start by considering the use of the standard scanf. If you write
scanf("%s", &str);
that will be incorrect (although it might work). When passing an array to a function it decays to a pointer to the first element, which is what scanf requires, so the line should be
scanf("%s", str);
If you want to restrict the input length to prevent buffer overflow it can be like this (one less than the array length to allow for the nul terminator)
scanf("%126s", str);
The allegedly safer function scanf_s requires an additional size argument to be passed for each format type %c and %s and %[] so the next line (after correcting the &)
scanf_s("%s", str);
lacks that argument, and the compiler should issue a warning about it. The code should be
scanf_s("%s", str, sizeof str);
but even that is inadequate. The Xscanf family of functions returns the number of values successfully entered. Since users (even myself) are notoriously bad at entering correct input (which may even be malicious) you must always check if the data was correctly entered. Such as
if(scanf_s("%s", str, sizeof str) != 1) {
// inform user and retry etc. etc.
}
As mentioned by #chux it is better to obtain input by using fgets, and then process it by various means, such as sscanf or strtok or strsep or by more direct analysis of the string. In that case, and with sscanf, you can make multiple attempts to process the input, but with scanf you only get one chance. Note that strtok and strsep modify the string, so you would need to work with a copy if you need to make more than one attempt to decode it.
In your second example
scanf_s("%d", &str);
you got "no exception but a long and strange string", but you should have got a compiler warning:
warning C4477: 'scanf_s' : format string '%d' requires an argument of
type 'int ', but variadic argument 1 has type 'char ()[127]'
Note that you did not initialise str to the "empty string" and if you go on to process what you imagine to be a good string after a faulty input, bad stuff can happen.

Related

Why is the output 6487620 (profit) by giving any input in this c program used to show profit or loss [duplicate]

#include <stdio.h>
#include <stdlib.h>
int main() {
char a;
printf("What? \t");
scanf("%s", &a);
printf("U have to %s", a);
return 0;
}
Whenever I build and run this code and enter a value in %s, I get an error and the debug program stops working and closes. But when I use ampersand sign like this:
#include <stdio.h>
#include <stdlib.h>
int main() {
char a;
printf("What? \t");
scanf("%s", &a);
printf("U have to %s", &a);
return 0;
}
in the printf... it works. Why is that? It also differs between the format specifier, such as one doesn't need to put & (ampersand) sign in printf when one uses %c or %d in the scanf. Why does this happen and is it related to the data types and which format specifiers concludes this result?
(sorry for my bad English. I am not a native English speaker and this is my first time here).
What you have here is a classic example of code that seems to work, but for the wrong reasons.
Let's review a few things about printf and scanf. The format specifier %d is for values of type int. You can read an integer like this:
int i;
scanf("%d", &i);
And you can print it back out like this:
printf("%d\n", i);
Why does one use an & and one does not? Well, C uses what's called "pass by value". If we wrote
scanf("%d", i); /* WRONG */
we would be passing the value of i to scanf. But we don't want to pass the (old) value of i to scanf, we want scanf to read a new value, and store it into i. In other words, we want scanf to, in effect, pass the new value of i back to us. For that to work, we instead pass scanf a pointer to the variable i where we want it to store the just-read integer. That's what the & does -- it generates a pointer to i.
When we call printf, on the other hand, the regular way of passing arguments works just fine. We do want to pass i's value to printf so that it can print it out. If we were to call
printf("%d\n", &i); /* WRONG */
it wouldn't work, because printf expects an int, and here we're wrongly handing it a pointer-to-int.
So now we've learned that for integers with %d, printf wants an int and scanf wants a pointer-to-int.
Let's talk about characters. The format %c is for characters. We can read one character with scanf:
char c;
scanf("%c", &c);
And we can print it with printf:
printf("%c\n", c);
Again, the pattern is exactly the same. scanf needs a pointer, so that it can fill in the value, so we pass &c. But printf just needs the value, so we pass plain c.
Now we get to strings. A string in C is an array of characters. Also strings in C are always terminated by a special null character, '\0', that marks the end of the string. So if we wanted to declare a variable that could contain strings up to 9 characters long, we might write
char s[10];
That gives us room for 9 characters, plus the terminating '\0'.
But arrays are special in C: Whenever you pass an array to a function, or whenever you do anything that would require the "value" of the array, what you get instead (what the compiler automatically generates for you) is a pointer to the array's first element.
What this means is that to read a string with scanf and %s, we can just call:
scanf("%s", s);
"But where is the &?", you ask. "I thought you always needed an & when calling scanf!"
Well, not quite. You always need a pointer when calling scanf. And in fact, when you called scanf("%s", s), it was just as if you had written
scanf("%s", &s[0]);
When you use %s with scanf, it expects a pointer to the first of several characters, that is, a pointer to the beginning of an array of characters, where it should begin writing the string it reads. (How does it know how big the array is? What if the user types a string that's too long to fit in the array? We'll get to those points in a moment.)
You can print strings with %s too, of course, and it looks like this:
printf("%s\n", s);
This is, again, just as if you had written
printf("%s\n", &s[0]);
When you use %s with printf, it expects a pointer to the first of several characters which it should begin printing, until it finds the terminating '\0' character.
So %s is special with printf and scanf, because strings are special (because arrays are special). With %d and %c and just about every other format specifier, you usually need a & when you call scanf, and you usually don't want that & when you call printf. But with %s, you usually don't want the & for either printf or scanf.
(And if we think about it a bit more carefully, the exception is not so much that scanf and %s does not need the &. Remember, the rule is really, scanf always needs pointers. The only reason scanf and %s doesn't need an & is that when you pass an array, you get a pointer to the array's first element automatically. So the exception is really for printf and %s: printf and %s does expect a pointer, and the reason printf and %s is designed to expect a pointer is that there's no way to not give it one: it has to accept a pointer, because for strings, that's what you always end up giving it.)
So the rule with %s is that scanf expects a pointer to the first of several characters, and printf expects a pointer to the first of several characters, too.
So now, with all that background out of the way, we can look at your code. You basically wrote
char c;
scanf("%s", &c);
At first this might seem to be kinda, sorta, almost correct. scanf and %s wants a pointer to a character, and you gave it &c, which is a pointer to a character. But %s really wants a pointer to the first of several characters. But you gave it a pointer to just a single character. So when the user types a string, the first character typed will get stored in c, but the rest of the characters, and the terminating '\0', will get written to unallocated memory somewhere off to the right of variable c. They'll overwrite ("clobber") memory that was, perhaps, used for something else. This is a serious problem, but it might not become evident right away.
Finally, you tried to print things out again with printf. You first tried
printf("%s\n", c); /* WRONG */
but this didn't work at all. The reason is that %s with printf expects a pointer-to-char, but you gave it a plain char. Suppose c contains the letter 'A'. This would end up asking printf to go to address 65 and begin printing characters until it finds the terminating '\0'. Why address 65? Because 65 is the ASCII code for A. But there's probably not a proper, null-terminated string starting at address 65 in memory; in fact there's a good chance your program doesn't have permission to read from address 65 at all.
So then you tried
printf("%s\n", &c); /* ALSO WRONG */
and this seemed to work. It "worked" because, if scanf succeeded in storing a complete string into c and the unallocated memory off to the right of it, and if clobbering that memory somehow didn't cause (too many) other problems, then when you pass the pointer &c to printf, printf can find those characters, making up a string, and print them out.
So it "works", but as I said, for the wrong reasons: in the process it stomps all over memory it doesn't "own", and sooner or later, something else is going to not work as a result.
How should you have scanned and printed a string? One way is like this, as we saw before:
char s[10];
scanf("%s", s);
printf("%s\n", s);
Now when scanf gets a pointer to the first element of the array s, it has 10 characters to play with.
We really do have to worry about the possibility that the user will type more than 9 characters. But there's a fix for that: we can tell scanf how long a string it's allowed to read, how many characters it's allowed to write to the array we handed it:
scanf("%9s", s);
That 9 in there tells scanf that it's not allowed to read more than 9 characters from the user. And since 9 is less than 10, there's still room for the terminating '\0' character.
There's much more that could be said about scanf. As chqrlie noted in a comment, it's important to check its return value, to make sure it succeeded in converting as many values as you wanted it to. It's got some strange rules about whitespace. Unless you know what you're doing, you can't intermix calls to scanf with calls to other input-reading functions like getchar or fgets -- you'll get strange results. And, finally, scanf is so persnickety and (in the end) so lacking in truly useful functionality that it's not really worth using at all. But those are topics for another day, since this answer is tl;dr already.
The %s format specifier requires a pointer to a string. When used with scanf, it must be a char array with enough characters for the word you enter plus the trailing null byte that indicates the end of the string. In printf() it has to be a null-terminated char array.
Using a pointer to a char variable doesn't work, because it doesn't have room for the null byte. You're causing undefined behavior by writing outside the variable.
char word[100];
scanf("%s", word);
printf("%s\n", word);
You can use %c to read and write a single character rather than a string of multiple characters.
char letter;
scanf("%c", &letter);
printf("%c\n", letter);
In statement char a; a is a character variable & to scan a char variable use %c format specifier.
scanf("%s",a);/* %s expects base address of char buffer, not single char */
scanf(" %c",&a);/* this is correct */
If you want to scan using %s then your input should be char buffer like char buf[10]. for e.g
char a[10];
scanf("%s",a);
u don't need to put &(ampersand) sign in printf when u use %c or %d ? no need to provide address & to printf() as printf() job is to print not to scan. for e.g
char input;
scanf("%c",&input);/* here you need &, As scanf() will store input char into
address you provided i.e &input */
printf("%c",input);/*here no need &input, bcz input char already stored,
printf will just print the char*/
Well, if you print the address you can use %p.
printf("%p",a);/*a is char buffer */

c - scanf not storing input properly

My code looks like this:
int nameFull;
printf("What is your name?\n");
scanf("%d\n", &nameFull); \\up until here it seems to work
printf("Hello %d", nameFull);
return 0;
But my output every time I run the program is "Hello 0" no matter what I input.
Does anyone know how to fix this?
First of all scanf() doesn't emit a prompt so its not a good idea to use any trailing whitespace character in the format string like \n here , It will cause it to read and discard character until next non-whitespace character.
To read a name you can do it like :
char name[50];
scanf("%49s",name); // 49 to limit the buffer input to prevent buffer overrun , this is a security issue.
You should also check the return value of scanf to see if the operation was successful. Personally , I don't prefer using scanf() at all because of various potential problems. It takes as input only what the program author expects it to, not considering other inputs which user might accidentally input. Check out here and here. Also check the scanf() man page
A better and safer method would be use fgets(),
fgets(name,sizeof(name),stdin);
You want to read a string, but you are an integer to store the input. That's not the right approach.
A better aproach would be to use an array of characters, to store the string in it.
char nameFull[100]; // can store up to 100 characters, 99 + 1 for the null-terminator ideally
Now, you could use scanf, like this:
scanf(" %99[^\n]", nameFull);
Note that I used 99, as a guard for not overflowing your array nameFull, if the user inputs too many characters for the size of your array. I didn't use %s, which would stop at a whitespace, and you seem to want to input a full name, which is usually two words and a space in between.
An alternative would be to use fgets(), which provides more safety, like this:
fgets(nameFull, sizeof(nameFull), stdin)
It will read the whole line though and store the trailing newline, while scanf() will read a single string.
Moreover, use the string identifier to print, not the integer one (%s is for string, %d is for integers). Like this:
printf("Hello %d", nameFull);
to this:
printf("Hello %s", nameFull);
as discussed about the string format.
%s reads a string of characters.
%d reads a integer.
So, your correct code will be like following code :
#include <stdio.h>
int main(){
char nameFull[100];
printf("What is your name?\n");
scanf("%99s", nameFull); //to avoid potential buffer overflow
printf("Hello %s\n", nameFull);
return 0;
}
N.B: Check this comment for nice explanation.
Well, int stores a number, a name is not a number. A name is a set of characters (aka strings). So this program would work (no error checking and such since you are in an introductory course):
char name[1024]; // 1024 is more than enough space for a name
scanf("%s", name); // %s reads a string of characters
printf("Hello %s\n", name);
return 0;
You are trying to assign an array of character (commonly referred as string) to an integer variable.
That's not correct.
Just change your variable as such
char nameFull[1024] = {0};
And then use scanf(3) with the appropriate format specifiers for strings, which is %s
scanf("%s", nameFull);
Normally you would check for the return of scanf to know if errors occurs, and in such cases, handle them.
Anyway, I would advice you to use fgets(3) which prevents buffer overflow
char *fgets(char *s, int size, FILE *stream);
fgets() reads in at most one less than size characters from stream and stores them into the buffer pointed to by s. Reading stops after an EOF or a newline. If a newline is read, it is stored into the buffer. A terminating null byte (aq\0aq) is stored after the last character in the buffer.

String input using C scanf_s

I've been trying to look for answer myself, but I can't find one.
I want to insert a part of the programming that reads in a string like "Hello" and stores and can display it when I want, so that printf("%s", blah); produces Hello.
Here's the code part that's giving me trouble
char name[64];
scanf_s("%s", name);
printf("Your name is %s", name);
I know that printf isn't the problem; the program crashes after something is input after a prompt. Please help?
From the specification of fscanf_s() in Annex K.3.5.3.2 of the ISO/IEC 9899:2011 standard:
The fscanf_s function is equivalent to fscanf except that the c, s, and [ conversion
specifiers apply to a pair of arguments (unless assignment suppression is indicated by a
*). The first of these arguments is the same as for fscanf. That argument is
immediately followed in the argument list by the second argument, which has type
rsize_t and gives the number of elements in the array pointed to by the first argument
of the pair. If the first argument points to a scalar object, it is considered to be an array of
one element.
and:
The scanf_s function is equivalent to fscanf_s with the argument stdin
interposed before the arguments to scanf_s.
MSDN says similar things (scanf_s() and fscanf_s()).
Your code doesn't provide the length argument, so some other number is used. It isn't determinate what value it finds, so you get eccentric behaviour from the code. You need something more like this, where the newline helps ensure that the output is actually seen.
char name[64];
if (scanf_s("%s", name, sizeof(name)) == 1)
printf("Your name is %s\n", name);
I used this very often in my university classes so this should work fine in Visual Studio (tested in VS2013):
char name[64]; // the null-terminated string to be read
scanf_s("%63s", name, 64);
// 63 = the max number of symbols EXCLUDING '\0'
// 64 = the size of the string; you can also use _countof(name) instead of that number
// calling scanf_s() that way will read up to 63 symbols (even if you write more) from the console and it will automatically set name[63] = '\0'
// if the number of the actually read symbols is < 63 then '\0' will be stored in the next free position in the string
// Please note that unlike gets(), scanf() stops reading when it reaches ' ' (interval, spacebar key) not just newline terminator (the enter key)
// Also consider calling "fflush(stdin);" before the (eventual) next scanf()
Ref: https://msdn.microsoft.com/en-us/library/w40768et.aspx
The scanf_s function is equivalent to scanf except that %c, %s, and %[ conversion specifiers each expect two arguments (the usual pointer and a value of type rsize_t indicating the size of the receiving array, which may be 1 when reading with a %c into a single char)
Your code doesn't provide the size of receiving array, also the variable name is a pointer pointing to the first character of the array, so it contains the address of name[0]. Therefore your first argument name in scanf_s is correct because name is a pointer, also note that, for the second argument you can't insert the size of a pointer like sizeof(name) because it is always same. You need to specify the size of your char array (name[64]), so for the second argument you should insert sizeof(name[64]) or 64*sizeof(char).
You can correct your code as follows:
char name[64];
if (scanf_s("%s", name, sizeof(name[64])) == 1)
printf("Your name is %s\n", name);
Here is a part of code that works for me fine:
char name[64];
scanf_s("%63s", name,(unsigned)_countof(name));
printf("Your name is %s", name);
For more information here is a link:
https://learn.microsoft.com/de-de/cpp/c-runtime-library/reference/scanf-s-scanf-s-l-wscanf-s-wscanf-s-l?view=msvc-170
Best Regards
#include<stdio.h>
int main()
{
char name[64];
printf("Enter your name: ");
scanf("%s", name);
printf("Your name is %s\n", name);
return 0;
}
#include<stdio.h>
int main()
{
char name[64];
printf("Enter your name: ");
gets(name);
printf("Your name is %s\n", name);
return 0;
}
you should do this : scanf ("%63s", name);
Update:
The below code worked for me:
#include <stdio.h>
int main(void) {
char name[64];
scanf ("%63s", name);
printf("Your name is %s", name);
return 0;
}
if you are using visual studio,
go to Project properties -> Configuration Properties -> C/C++-> Preprocessor -> Preprocessor Definitions click on edit and add _CRT_SECURE_NO_WARNINGS click ok, apply the settings and run again.
Note: this is only good if you are doing your homework or something like that and it's not recommended for production.

C - Not printing out the whole string

int main()
{
//Define Variables
char studentName;
//Print instructions to fill the data in the screen
printf("Please type in the Students name:\n");
scanf("%s", &studentName);
printf("\n\n%s", &studentName);
return 0;
}
Seeing the above code, I am only printing to screen out the first word when I type in a sentence.
I know it is a basic thing, but I am just starting with plain C.
Read scanf(3) documentation. For %s is says
s Matches a sequence of non-white-space characters; the next
pointer must be a pointer to character array that is long
enough to hold the input sequence and the terminating null
byte ('\0'), which is added automatically. The input string
stops at white space or at the maximum field width, whichever
occurs first.
So your code is wrong, because it should have an array for studentName i.e.
char studentName[32];
scanf("%s", studentName);
which is still dangerous because of possible buffer overflow (e.g. if you type a name of 32 or more letters). Using %32s instead of %s might be safer.
Take also the habit of compiling with all warnings enabled and with debugging information (i.e. if using GCC with gcc -Wall -g). Some compilers might have warned you. Learn to use your debugger (such as gdb).
Also, take the habit of ending -not starting- your printf format string with \n (or else call fflush, see fflush(3)).
Learn about undefined behavior. Your program had some! And it misses a #include <stdio.h> directive (as the first non-comment significant line).
BTW, reading existing free software code in C will also teach you many things.
There are three problems with your code:
You are writing a string into a block of memory allocated for a single character; this is undefined behavior
You are printing a string from a block of memory allocated for a single character - also an undefined behavior
You are using scanf to read a string with spaces; %s stops at the first space or end-of-line character.
One way to fix this would be using fgets, like this:
char studentName[100];
//Print instructions to fill the data in the screen
printf("Please type in the Students name:\n");
fgets(studentName, 100, stdin);
printf("\n\n%s", &studentName);
return 0;
Try scanf("%[^\n]", &studentName); instead of scanf("%s", &studentName);
This is happening because %s stops reading the input as soon as a white space is encountered.
To avoid this what you can do is declare an array of the length required for your string.
Then use this command to input the string:-
scanf("%[^\n]s",arr);
This way scanf will continue to read characters unless a '\n' is encountered, in other words you press the enter key on your keyboard. This gives a new line signal and the input stops.
int main()
{
//Define Variables
char studentName[50];
//Print instructions to fill the data in the screen
printf("Please type in the Students name:\n");
scanf("%[^\n]s", &studentName);
printf("\n\n%s", &studentName);
return 0;
}
Alternatively you can also use the gets() and puts() method. This will really ease your work if you are writing a code for a very basic problem.
[EDIT] : As dasblinkenlight has pointed out...I will also not recommend you to use the gets function since it has been deprecated.
int main()
{
//Define Variables
char studentName[50];
//Print instructions to fill the data in the screen
printf("Please type in the Students name:\n");
gets(studentName); printf("\n\n");
puts(studentName);
return 0;
}
make the changes below and try it. I added [80] after the studentName definition, to tell the compiler that studentName is an array of 80 characters (otherwise the compiler would treat it as only one char). Also, the & symbol before studentName is not necessary, because the name of the array implicitly implies a pointer.
int main()
{
//Define Variables
char studentName[80];
//Print instructions to fill the data in the screen
printf("Please type in the Students name:\n");
scanf("%s", studentName);
printf("\n\n%s", studentName);
return 0;
}
Your problem is here
char studentName;
It is a char, not a string.
Try:
Define it as an array of chars like char studenName[SIZE];.
allocating memory dynamically using malloc:
.
char buffer[MAX_SIZE];
scanf("%s", &buffer);
char * studentName = malloc (sizeof(buffer) + 1);
strcpy (studentName , buffer);

C program using printf & scanf crashes on input

I am writing following c code and getting an error :
#include<stdio.h>
#include<stdlib.h>
int main()
{
char *prot;
char addr[20];
FILE *fp;
int i = 0;
int tos,pld;
prot = (char *)malloc(sizeof(char *));
//addr = (char *)malloc(sizeof(char *));
printf("\n enter the protocol for test::");
scanf(" %s",prot);
printf("\n enter the addr::");
scanf(" %s",addr);
printf("\n enter the length of the payload::");
scanf(" %d",pld);
printf("\n enter the tos :: ");
scanf(" %d",tos);
I am getting the following error while entering the value.There is a segmentation fault coming could anyone tell me why this segment fault is coming:
enter the protocol for test::we
enter the addr::qw
enter the length of the payload::12
Segmentation fault
prot = (char *)malloc(sizeof(char *));
Should be:
prot = malloc(sizeof(char) * SIZE); // SIZE is the no. of chars you want
Another problem is: You should use & for integers in scanf()!
With changes:
printf("\n enter the length of the payload::");
scanf(" %d",&pld);
printf("\n enter the tos :: ");
scanf(" %d",&tos);
The segmentation fault is because scanf expects a pointer to the variable the scanned value shall be stored in, but you pass the variable pld itself. That is uninitialised and hence when interpreted as a pointer points into the wild. The same happens with the tos. And of course, you should allocate the proper amount of space for prot as has otherwise been pointed out.
Your memory allocation for prot has allocated 4 bytes (on a 32-bit system) or 8 bytes (on a 64-bit system) for the string. If you read more than that into it, you are overflowing your buffer.
Unless there was a good reason to do otherwise, I'd simply use:
char prot[128];
for any suitable size for the string.
You should also check all your scanf() calls to ensure they succeed; you should probably apply a limit to the size of the strings. For a char prot[128];, the safe conversion is %127s; the null is not counted in the conversion specification.
If your compiler was not warning you about these lines:
scanf(" %d",pld);
scanf(" %d",tos);
you either need to turn on more warnings or get a better compiler. If it was warning you, pay heed to your compiler; it knows more about C than you do (and probably more about it than I do, too).
scanf(" %d", &pld);
scanf(" %d", &tos);
This is probably not the source of your current problem, but it is a bug:
prot = (char *)malloc(sizeof(char *));
I doubt you meant to make a buffer the size of one character pointer.
Anyway, to pinpoint your immediate issue, please run your program under valgrind and/or a debugger. In this particular case just enabling compiler warnings would have caught your problem, which is that you're passing integers by value where you should be passing by pointer to scanf. This could have been solved by the compiler, instead of coming to us, if only you enable the relevant options.
scanf expects pointers to the variables you're filling (except in the case of strings, which are already pointers to char).
Try
scanf(" %d", &pld);
and the same with tos.
scanf family of functions are main source of problems in homework.
They always expect addresses, so they can be used as OUTPUT.
They cannot be type-checked because the prototype of that part is ..., so you can put anything there. compiler does not complain.
When things don't work, check the receiver arguments, they need to be address of items to be written into, and the type has to match what your specify in the format string.

Resources