i use a scanf to get user input but if i press enter, the cursor will flash to next line~
what function should i use instead of scanf if i want the program will terminated if the users only press enter without keying any thing?
thanks
Scanf reads until the next token -- it doesn't really care about newlines at all (just considers them to be whitespace, like spaces or tabs).
Instead, use a line-reading function like fgets.
you can use gets() function in this way :
#include <stdio.h>
#define MAX_INPUT_CHAR 100
int main( ) {
char str[MAX_INPUT_CHAR ];
printf( "Enter a value :");
gets( str );
return 0;
}
Function char *gets(char *s) reads a line from stdin into the buffer pointed to by
s until either a terminating newline or EOF (End of File)
Pay attention gets() is not safe. You can't now apriori how much character it will read. This can cause some security problem and eventually crash.
Just use this code :
char ch;
printf("Enter Your Sentence \n");
while (1)
{
ch = getch();
if ((int)ch == 13)
break;
printf("%c", ch);
}
I disagree:
char * x;
scanf("%s",x);
printf("Inserted line: %s\n",x);
Will store in x only the characters till the return key.
I build it and runned it and it works.
Related
int main(){
char str[10][50],temp[50];
int lim,i,j;
printf("Enter lim: ");
scanf("%d",&lim);
for(i=0;i<lim;++i){
printf("Enter string[%d]: ",i+1);
gets(str[i]);
}
Here the str[0](Enter string[1]: ) can't be read. The reading starts from 'Enter string[2]: '(str[1]).
But if instead of lim, an integer is passed to loop as below, program executes correctly. What may be reason for this scenario ?
int main(){
char str[10][50],temp[50];
int lim,i,j;
for(i=0;i<5;++i){
printf("Enter string: ");
gets(str[i]);
}
Your scanf() for the number has left a newline in the input stream, which will feed the first gets().
Have a look here for help:
http://sekrit.de/webdocs/c/beginners-guide-away-from-scanf.html
How to read / parse input in C? The FAQ
Also, you do not want to use gets() anymore.
Why is the gets function so dangerous that it should not be used?
Firstly don't use gets() use fgets() instead. From the manual page of gets()
Never use gets(). Because it is impossible to tell without knowing the
data in advance how many characters gets() will read, and because
gets() will continue to store characters past the end of the buffer,
it is extremely dangerous to use. It has been used to break computer
security. Use fgets() instead.
Secondaly stdin is line buffered, when you use scanf() like scanf("%d",&lim); and press ENTER, the newline \n char is left into stdin stream that causes gets() to not to read str[0].
For e.g
for(i=0;i<lim;++i){
printf("Enter string[%d]:\n ",i);
fgets(str[i],sizeof(str[i]),stdin);
}
Also note that when you use fgets() it will store \n into buffer at the end. If you don't want \n at the end of str[index] you have to remove it.
Also don't Forget to check the return value of fgets().
For e.g
char *ptr = NULL;
ptr=fgets(str[i],sizeof(str[i]),stdin);
if( ptr != NULL && str[strlen(str[i])-1] == '\n'){
str[strlen(str[i])-1] = '\0'; /* replace \n with \0 */
}
I am using this method to find a space or specified word in string.
but this method doesn't works. I've checked the flow many times.
#include <stdio.h>
int main()
{
char text[50], find;
int i = 0, sp = 0;
printf("Enter text: \n");
scanf("%s", text);
printf("Enter a char to find:\n");
scanf("%c", &find);
while ( text[i] != '\0') // to receive a value untill enter is pressed.
{
if (text[i] == find) // count if text[i] is the specified value.
{ sp++; }
i++;
}
printf("%d", sp); // prints 0 always. how to fix this.
}
The find in your code is always assigned with \n or the new line character that you enter at the end of scanning your string text .Try giving a space in scanf statement of find :
scanf(" %c",&find)
Why to give a space?
By giving a space,the compiler omits the '\n' character from the previous scanf
Note: scanf("%s",string) ends scanning when it encounters white space i.e, '\n' or '\0' or '\t' but to account for spaces, try
using this scanf("%[^\n]s",string")
You cannot use scanf() to read a string of characters with space. As soon as the space is encountered, scanf() exits.
Use fgets() instead.
And as for finding a word in the string, to compare strings use strcmp().
SIDE NOTE:
1) Check the return values of scanf()
2) Use the standard definition of main()
int main(void) //if no command line arguments.
I found a solution for that:
scanf("%[^\n]", fullName);
works fine. and receives whole line
getchar() is not working in the below program, can anyone help me to solve this out. I tried scanf() function in place of getchar() then also it is not working.
I am not able to figure out the root cause of the issue, can anyone please help me.
#include<stdio.h>
int main()
{
int x, n=0, p=0,z=0,i=0;
char ch;
do
{
printf("\nEnter a number : ");
scanf("%d",&x);
if (x<0)
n++;
else if (x>0)
p++;
else
z++;
printf("\nAny more number want to enter : Y , N ? ");
ch = getchar();
i++;
}while(ch=='y'||ch=='Y');
printf("\nTotal numbers entered : %d\n",i);
printf("Total Negative Number : %d\n",n);
printf("Total Positive number : %d\n",p);
printf("Total Zero : %d\n",z);
return 0 ;
}
The code has been copied from the book of "Yashvant Kanetkar"
I think, in your code, the problem is with the leftover \n from
scanf("%d",&x);
You can change that scanning statement to
scanf("%d%*c",&x);
to eat up the newline. Then the next getchar() will wait for the user input, as expected.
That said, the return type of getchar() is int. You can check the man page for details. So, the returned value may not fit into a char always. Suggest changing ch to int from char.
Finally, the recommended signature of main() is int main(void).
That's because scanf() left the trailing newline in input.
I suggest replacing this:
ch = getchar();
With:
scanf(" %c", &ch);
Note the leading space in the format string. It is needed to force scanf() to ignore every whitespace character until a non-whitespace is read. This is generally more robust than consuming a single char in the previous scanf() because it ignores any number of blanks.
When the user inputs x and presses enter,the new line character is left in the input stream after scanf() operation.Then when try you to read a char using getchar() it reads the same new line character.In short ch gets the value of newline character.You can use a loop to ignore newline character.
ch=getchar();
while(ch=='\n')
ch=getchar();
When you using scanf getchar etc. everything you entered stored as a string (char sequence) in stdin (standard input), then the program uses what is needed and leaves the remains in stdin.
For example: 456 is {'4','5','6','\0'}, 4tf is {'4','t','f','\0'} with scanf("%d",&x); you ask the program to read an integer in the first case will read 456 and leave {'\0'} in stdin and in the second will read 4 and leave {''t','f',\0'}.
After the scanf you should use the fflush(stdin) in order to clear the input stream.
Replacing ch = getchar(); with scanf(" %c", &ch); worked just fine for me!
But using fflush(stdin) after scanf didn't work.
My suggestion for you is to define a Macro like:
#define __GETCHAR__ if (getchar()=='\n') getchar();
Then you can use it like:
printf("\nAny more number want to enter : Y , N ? ");
__GETCHAR__;
I agree that it is not the best option, but it is a little bit more elegant.
Add one more line ch = getchar();
between scanf("%d",&x); and ch = getchar();
then your code work correctly.
Because when you take input from user, in this time you press a new line \n after the integer value then the variable ch store this new line by this line of code ch = getchar(); and that's why you program crash because condition can not work correctly.
Because we know that a new line \n is also a char that's why you code crash.
So, for skip this new line \n add one more time ch = getchar();
like,
ch = getchar(); // this line of code skip your new line when you press enter key after taking input.
ch = getchar(); // this line store your char input
or
scanf("%d",&x);
ch = getchar(); // this line of code skip your new line when you press enter key after taking input.
pieces of code work correctly.
the idea is that i type in a sentence and store it as a string... then i can choose a letter and change it to a different letter
int main(int argc, char *argv[])
{
char string[100];
char newLetter;
char oldLetter;
int i = 0;
printf("Please enter your sentence : ");
gets(string);
printf("\n\nWord is : %s" , string );
printf("\n\nTarget : ");
scanf("%s", &oldLetter);
printf("Replace with : ");
scanf("%s", &newLetter);
for ( i = 0; i < sizeof(string); i++)
{
if (string[i] == oldLetter)
{
string[i] = newLetter;
break;
}
}
printf("\n\nWord is : %s" , string );
system("PAUSE");
return 0;
}
any help in where I've gone wrong is appreciated
eg.
input could be - yellow lorry red lorry
then target - r
change to - t
output - yellow lotty ted lotty
Change the %s in the scanning of the two letters to %c and the code will run flawlessly.
First things first, since you are aiming to store a character to char oldLetter and char newLetter via scanf, you should be using the format specifier %c instead of the %s.
However, that won't be enough, because of the following: When you use functions like scanf or gets, you prompt user to input characters to the stdin stream. stdin stream is a buffered stream. You may think of it as a:
Stream of river that you;
drop characters into
each character you drop remains inside the river
until something takes them out
When scanf comes, and you type, say, A and then press the enter key, you put the following characters in the stream:
'A' '\n'
Where \n is the new-line character. With the enter key-press, you also inform the scanf that you're done. scanf then starts issuing the stdin buffer, let's see... 'A', a proper value for %c character. It takes that one out, leaves \n behind.
Then the next scanf comes, seeks for a %c in stream, finds the \n ready, takes that out. This is what you wouldn't want. Two ways to prevent it:
use fflush( stdin ); after the scanf calls, or
use while( getchar( ) != '\n' ); after the scanf calls
to dismiss/discard the remaining characters in the buffer.
And get rid of that break; if you want to replace each occurrence and not just the first one.
You can do it right, or you can do it wrong and hope that the person doesn't enter the right series of keystrokes or pipe in a file that doesn't end in newline, to break it ... up to you
I have a difficulty understanding getchar(). In the following program getchar works as expected:
#include <stdio.h>
int main()
{
printf("Type Enter to continue...");
getchar();
return 0;
}
However, in the following program, getchar does not create a delay and the program ends:
#include <stdio.h>
int main()
{
char command[100];
scanf("%s", command );
printf("Type Enter to continue...");
getchar();
return 0;
}
I have the following weired workaround, which works, but I don't understand why:
#include <stdio.h>
int main()
{
char command[100];
int i;
scanf("%s", command );
printf("Type Enter to continue...");
while ( getchar() != '\n') {
i=0;
}
getchar();
return 0;
}
So my questions are:
1. What is scanf doing? Why does scanf do this ?
2. Why is my work around working?
3. What is a good way to emulate the following Python code:
raw_input("Type Enter to continue")
The input is only sent to the program after you typed a newline, but
scanf("%s", command );
leaves the newline in the input buffer, since the %s(1) format stops when the first whitespace character is encountered after some non-whitespace, getchar() then returns that newline immediately and doesn't need to wait for further input.
Your workaround works because it clears the newline from the input buffer before calling getchar() once more.
To emulate the behaviour, clear the input buffer before printing the message,
scanf("%s", command);
int c;
do {
c = getchar();
}while(c != '\n' && c != EOF);
if (c == EOF) {
// input stream ended, do something about it, exit perhaps
} else {
printf("Type Enter to continue\n");
getchar();
}
(1) Note that using %s in scanf is very unsafe, you should restrict the input to what your buffer can hold with a field-width, scanf("%99s", command) will read at most 99 (sizeof(command) - 1)) characters into command, leaving space for the 0-terminator.
Whitespace is a delimiter for 5y3 %s format specifier, and newline is regarded as whitespace, so it remains buffered. Console input is normally line oriented, so a subsequent call to getchar() will return immediately because a 'line' remains buffered.
scanf("%s", command );
while( getchar() != '\n' ){ /* flush to end of input line */ }
Equally if you use getchar() or %c to get a single character you normally need to flush the line, but in this case the character entered may itself be a newline so you need a slightly different solution:
scanf("%c", ch );
while( ch != '\n' && getchar() != '\n' ){ /* flush to end of input line */ }
similarly for getchar():
ch = getchar();
while( ch != '\n' && getchar() != '\n' ){ /* flush to end of input line */ }
The sensible thing to do of course is to wrap these solutions into stand-alone specialised input functions that you can reuse and also use as a place to put common input validation and error checking code (as in Daniel Fischer's answer which sensibly checks for EOF - you would normally want to avoid having to duplicate those checks and error handling everywhere).
I'd rather first use fgets and then use sscanf to parse the input. I have been doing this stuff like this for a long time and the behaviour has been more predictable than using plain scanf.
Well, I have something easier: add another getchar() ... problem solved!!
after taking command input flush the stdin.
fflush(stdin);
but flushing a input stream results in undefined behavior (though Microsoft's C library defines the behaviour as an extension).