Take input string in c - c

To take input string in c, we can opt for 2 ways(as per my knowledge please add more if i missing something)
char name[10];
scanf(" %s",name); // First case
scanf("%[\n]s",name); // Second case
1st one will consider the string till the first blank space and 2nd will take complete sentence till the new line break as a string but to take input we need to improvise the 2nd statement as
scanf(" %[\n]s",name);
my question is what is extra spacing doing here ?
because sometime my compiler will behave normally even if i will remove the 's' from scanf statement and without extra spacing before '%' but sometime it wont work.

The space before the % operator will make it so that any white-space before the entered string is removed as well as whatever effect the format specifiers after the % operator have on the input.
Ex: "\n\t Hello World" entered with " %[^\n]" will be recorded as "Hello World".

If white space character is left in first input stream and mistakenely read by next input scanf: to delete the white space character from input stream either use space before format string or use fflush (stdin) function.

Related

Why is this creating two inputs instead of one

https://i.imgur.com/FLxF9sP.png
As shown in the link above I have to input '<' twice instead of once, why is that? Also it seems that the first input is ignored but the second '<' is the one the program recognizes.
The same thing occurs even without a loop too.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(){
int randomGen, upper, lower, end, newRandomGen;
char answer;
upper = 100;
lower = 1;
end = 1;
do {
srand(time(0));
randomGen = rand()%(upper + lower);
printf("%d\n", randomGen);
scanf("%s\n", &answer);
}while(answer != '=');
}
Whitespace in scanf format strings, like the \n in "%c\n", tries to match any amount of whitespace, and scanf doesn’t know that there’s no whitespace left to skip until it encounters something that isn’t whitespace (like the second character you type) or the end of input. You provide it with =\n, which fills in the %c and waits until the whitespace is over. Then you provide it with another = and scanf returns. The second time around, the character could be anything and it’d still work.
Skip leading whitespace instead (and use the correct specifier for one character, %c, as has been mentioned):
scanf(" %c", &answer);
Also, it’s good practice to make sure you actually succeeded in reading something, especially when failing to read something means leaving it uninitialized and trying to read it later (another example of undefined behaviour). So check scanf’s return value, which should match the number of conversion specifiers you provided:
if (scanf(" %c", &answer) != 1) {
return EXIT_FAILURE;
}
As has been commented, you should not use the scanf format %s if you want to read a single character. Indeed, you should never use the scanf format %s for any purpose, because it will read an arbitrary number of characters into the buffer you supply, so you have no way to ensure that your buffer is large enough. So you should always supply a maximum character count. For example, %1s will read only one character. But note: that will still not work with a char variable, since it reads a string and in C, strings are arrays of char terminated with a NUL. (NUL is the character whose value is 0, also sometimes spelled \0. You could just write it as 0, but don't confuse that with the character '0' (whose value is 48, in most modern systems).
So a string containing a single character actually occupies two bytes: the character itself, and a NUL.
If you just want to read a single character, you could use the format %c. %c has a few differences from %s, and you need to be aware of all of them:
The default maximum length read by %s is "unlimited". The default for %c is 1, so %c is identical to %1c.
%s will put a NUL at the end of the characters read (which you need to leave space for), so the result is a C string. %c does not add the NUL, so you only need to leave enough space for the characters themselves.
%s skips whitespace before storing any characters. %c does not ignore whitespace. Note: a newline character (at the end of each line) is considered whitespace.
So, based on the first two rules, you could use either of the following:
char theShortString[2];
scanf("%1s", theShortString);
char theChar = theShortString[0];
or
char theChar;
scanf("%c", &theChar);
Now, when you used
scanf("%s", &theChar);
you will cause scanf to write a NUL (that is, a zero) in the byte following theChar, which quite possibly is part of a different variable. That's really bad. Don't do that. Ever. Even if you get away with it today, it will get you into serious trouble some time soon.
But that's not the problem here. The problem here is with what comes after the %s format code.
Let's take a minute (ok, maybe half an hour) to read the documentation of scanf, by typing man scanf. What we'll see, quite near the beginning, is: (emphasis added)
A directive is one of the following:
A sequence of white-space characters (space, tab, newline, etc.; see isspace(3)). This directive matches any amount of white space, including none, in the input.
So when you use "%s\n", scanf will do the following:
skip over any white-space characters in the input buffer.
read the following word up to but not including the next white-space character, and store it in the corresponding argument, followed by a NUL.
skip over any white-space following the word which it just read.
It does the last step because \n — a newline — is itself white-space, as noted in the quote from the manpage.
Now, what you actually typed was < followed by a newline, so the word read at step 2 will be just he character <. The newline you typed afterwards is white-space, so it will be ignored by step 3. But that doesn't satisfy step 3, because scanf (as documented) will ignore "any amount of white space". It doesn't know that there isn't more white space coming. You might, for example, be intending to type a blank line (that is, just a newline), in which case scanf must skip over that newline as well. So scanf keeps on reading.
Since the input buffer is now empty, the I/O library must now read the next line, which it does. And now you type another < followed by a newline. Clearly, the < is not white-space, so scanf leaves it in the input buffer and returns, knowing that it has done its duty.
Your program then checks the word read by scanf and realises that it is not an =. So it loops again, and the scanf executes again. Now there is already data in the input buffer (the second < which you typed), so scanf can immediately store that word. But it will again try to skip "any amount of white space" afterwards, which by the same logic as above will cause it to read a third line of input, which it leaves in the input buffer.
The end result is that you always need to type the next line before the previous line is passed back to your program. Obviously that's not what you want.
So what's the solution? Simple. Don't put a \n at the end of your format string.
Of course, you do want to skip that newline character. But you don't need to skip it until the next call to scanf. If you used a %1s format code, scanf would automatically skip white-space before returning input, but as we've seen above, %c is far simpler if you only want to read a single character. Since %c does not skip white-space before returning input, you need to insert an explicit directive to do so: a white-space character. It's usual to use an actual space rather than a newline for this purpose, so we would normally write this loop as:
char answer;
srand(time(0)); /* Only call srand once, at the beginning of the program */
do {
randomGen = rand()%(upper + lower); /* This is not right */
printf("%d\n", randomGen);
scanf(" %c", &answer);
} while (answer != '=');
scanf("%s\n", &answer);
Here you used the %s flag in the format string, which tells scanf to read as many characters as possible into a pre-allocated array of chars, then a null terminator to make it a C-string.
However, answer is a single char. Just writing the terminator is enough to go out of bounds, causing undefined behaviour and strange mishaps.
Instead, you should have used %c. This reads a single character into a char.

scanf("%[^\n]s",a) with set size of string

So I had a code where I use
scanf("%[^\n]s",a);
and has multiple scanf to take different inputs some being string input. So I understand that scanf("%[^\n]s",a) takes input until new line has been reached, however I was wondering suppose my string can only hold up to 10 characters, then after my string has been filled, but new line hasn't been reached how can i get rid of the extra input before going to new line. I was thinking of doing getchar() until new line has been reached however in order to even check if my 10 spots has been filled I need to use getchar, so doesn't that mess up my next scanf input? Anybody have any other way to do it? Still using scanf() and getchar?
scanf("%[^\n]s",a) is a common mistake; the %[ directive is distinct from the %s directive. What you're asking from scanf is:
A group of non-'\n' characters, followed by...
A literal s character.
Perhaps you intended to write scanf("%[^\n]",a)? Note the deleted s...
You can use the * modifier to suppress assignment for a directive, for example scanf("%10[^\n]", a); followed by scanf("%*[^\n]"); to read and discard up to the next newline and getchar(); to read and discard that newline:
scanf("%10[^\n]", a);
scanf("%*[^\n]"); // read and discard up to the next newline
getchar(); // read and discard that newline
As pointed out, the two format strings could be concatenated to reduce the number of calls to scanf. I wrote my answer this way for the sake of documentation, and I'll leave it as is. Besides, I figure that attempt at optimisation would be negligible; a profiler is likely to indicate much more significant bottlenecks for optimisation in realistic scenarios.
You can use this format to hold the first 10 characters and keep the next lines of input:
scanf("%10[^\n]%*[^\n]",a);
getchar();

scanf() behaviour for strings with more than one word

Well I've been programming in C for quite a while now, and there is this question about the function scanf()
here is my problem:
I know that every element in ASCII table is a character and I even know that %s is a data specified for a string which is a collection of characters
My questions:
1.why does scanf() stops scanning after we press enter. If enter is also character why cant it be added as a component of the string that is being scanned.
2.My second question and what I require the most is why does it stops scanning after a space, when space is again a character?
Note: My question is not about how to avoid these but how does this happen
I'd be happy if this is already addressed, I'd gladly delete my question and even if I've presumed something wrong please let me know
"why does scanf() stops scanning after we press enter." is not always true.
The "%s" directs scanf() as follows
char buffer[100];
scanf("%s", buffer);
Scan and consume all white-space including '\n' generated from multiple Enters. This data is not saved.
Input white-space characters (as specified by the isspace function) are skipped, unless the specification includes a [, c, or n specifier C11dr §7.21.6.2 8
Scan and save all non-white-space characters. Continue doing so until a white-space is encountered.
Matches a sequence of non-white-space characters §7.21.6.2 12
This white-space is put back into stdin for the next input function. (OP's 2nd question)
A null character is appended to buffer.
Operations may stop short if EOF occurs.
If too much data is save in buffer, it is UB.
If some non-white-space data is saved, return 1. If EOF encountered, return EOF.
Note: stdin is usually line buffered, so no keyboard data is given to stdin until a '\n' occurs.
From my reading of your question, both of your numbered questions are the same:
Why does scanf with a format specifier of %s stop reading after encountering a space or newline.
And the answer to both of your questions is: Because that is what scanf with the %s format specifier is documented to do.
From the documentation:
%s Matches a sequence of bytes that are not white-space characters.
A space and a newline character (generated by the enter key) are white-space characters.
I made miniprogram with scanf for get multiple name without stop on space or ever enter.
i use while
Scanf("%s",text);
While (1)
{
Scanf("%s",text1)
If (text1=='.'){break;}
//here i simple add text1 to text
}
This way i get one line if use the .
Now i use
scanf("%[^\n]",text);
It work great.

C string using pointer

So, I want to get 5 string inputs from the user using array of pointers to strings. However, I want those strings to have white spaces and hence, I am using the %[^\n]s which accepts the string till a line break occurs. But, this code doesn't work :/ Can someone please explain why??
P.S-> If you use %s in scanf, the code works. But I want white spaces compulsorily. So, please suggest something.
Thanks in advance!
#include<stdio.h>
#include<malloc.h>
void main()
{
char *f[5];
int i;
printf("\nEnter 5 strings:\n");
for(i=0;i<5;i++)
f[i]=malloc(20);
for(i=0;i<5;i++)
scanf("%[^\n]s",f[i]);
printf("The 5 strings are:\n");
for(i=0;i<5;i++)
{
printf("\n%s",f[i]);
}
}
One major problem is the trailing 's' in your format. If you read e.g. this reference you will see that the "%[" format is terminated by the ']' character. When you have that extra 's' in the format, scanf will wait until it matches a literal 's' in the input.
And to skip the ending newline, you can add a leading whitespace in the format and scanf will automatically read and skip all whitespace (including newline) that you don't want in the next iteration of the loop.
You also should limit the length of the input scanf reads, or you might have scanf read more than you have allocated. The limit should be 19 characters (which with the string terminator is 20, like you have allocated).
So the correct format should be " %19[^\n]".
As a side-note, since you allocate all strings equally, why not simply have an array of arrays? Like
char f[5][20];
And if you still decide to go with the pointers, don't forget to free them when you're done. You don't really need it in such a simple case such as your program, but it's better to get the good habits early.
You just need to 'consume' the '\n' character after you've read what you want. Use the following format directive:
"%[^\n]%*c"
Which will read everything up to the newline into the string you pass in, then will consume a single character (the newline) without assigning it to anything (that '*' is 'assignment suppression').

Storing inputted characters in an array

I have to enter chars in C. Input is of the form:
'f' 'g'
'd' 'b'
'2' '3'
Each line has a pair of two characters, and my task is to store them in two different arrays. One array will store {'f','d','2'} and the other will store {'g','b','3'}.
My code is this:
for(i=0;i<n;i++){
scanf(" %c",&arr1[i]);
scanf("%c",&arr2[i]);
}
where n is the no. of rows.
There is no error but no values are stored in the second array.
Your code looks fine except you need space before %c in second scanf too:
for(i=0;i<n;i++){
scanf(" %c",&arr1[i]);
scanf(" %c",&arr2[i]);
}
A space before %c in scanf can skip any number of white-spaces. In absence of it, second scanf reads the white-spaces and store that in arr2.
==> Live Demo.
If your input is f, you press enter, and then g - then your second scanf call will consume the new line between the letters.
scanf("%c", ... Will read next character (this includes white space so it may read blank character).
scanf(" %c", ... Will skip white-space and read in next non-white-space character.
Note: New lines ('\n') are also considered white-space.
I mean, since you've told us that the input is of form like you've shown to us, there apparently are 's and spaces to be discarded. If so, it is almost as if you have to parse an input...
If you are certain that the input will be of the form you've described, then one way to do it would be to:
Read and discard until the first single-quote, then also the single-quote
Read and store the following character
Read and discard the following single-quote
Do this once again
On each loop. What I have described above, could be achieved with the following block consisting of a single scanf call, where the format-string is the important part:
for ( ... ) {
scanf( "%*[^']'%c'%*[^']'%c'", &arr1[i], &arr2[i] );
}
This assumes that the input will be of the form as displayed on the question, with a single-character inside single-quotes, arbitrarily spaced, and like that.
%*[^']' part handles the first bullet on the list above
%c and the paired &arr1[i] does the second
' does the third
Rest does the fourth
I know that, as per asker's comment, that this is not what's being looked for, however I felt like there should at least be an answer addressing what the question says and not just what the asker thinks, with the hope that it helps anybody.

Resources