Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I have an assignment where i need to find out what scanf("%*[^\n]"); does in a c program. I know that [^\n] means that the input is read until \n and that %* puts the input in the buffer and discards it. I don't understand what usage you can get out of it, because in my understanding it just reads the input till \n and discards it then.
scanf(“%*[^\n]”); usage in a c programm?
It is somewhat common to see yet fgets() is a better approach. Recommend to not use scanf() until you know why you should not use it. Then use it in a limited way.
I don't understand what usage you can get out of it
Example usage: code attempts to read numeric text with scanf("%d", &x); but "abc\n" is in stdin so function returns 0 and data in stdin remains. scanf("%*[^\n]"); clears out (reads and discards) the "abc" in preparation for a new line of input.
int x;
int count;
do {
puts("Enter number");
count = scanf("%d", &x); // count is 0, 1 or EOF
if (count == 0) {
scanf("%*[^\n]"); // Read and discard input up, but not including, a \n
scanf("%*1[\n]"); // Read and discard one \n
}
} while (count == 0);
if (count == EOF) puts("No more input");
else puts("Success");
Variations like scanf(" %*[^\n]"); and scanf("%*[^\n]%*c"); have their own corner problems (1st consume all leading white-space, even multiple lines, 2nd fails to read anything if the next character is '\n').
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed last year.
Improve this question
char *text;
text = malloc(256);
printf("Enter a sentence:");
scanf("%[^\n]s", text);
printf("%s",text);
Why doesn't the scanf function work in this code?
I don't enter a sentence and immediately the program finished.
scanf("%[^\n]s", text); is worse than gets(). text[] remains unassigned if only "\n" entered *1, possible buffer overflow with no width limit. The s in for format serves no purpose.
Instead use fgets() with its input limit. Check return value.
#define N 256
char *text = malloc(N);
printf("Enter a sentence:");
if (fgets(test, N, stdin)) {
test[strcspn(test, "\n")] = '\0'; // Lop off potential trailing \n
printf("%s\n",text);
}
OP may also have trouble due to a prior scanf() calls that leaves a dangling '\n' in stdin that chokes on this scanf("%[^\n]s".... Avoid using scanf() at all until you know why it is weak.
Sigh - if you must stay with scanf(), use below which 1) uses a leading space to consume all prior white-space like left-over '\n', 2) has a width limit and 3) tests the scanf() success.
if (scanf(" %255[^\n]", text) == 1) { // No 's' in format.
printf("%s\n",text);
}
*1 This explains the "I don't enter a sentence and immediately the program finished." as prior input did not consume a '\n' and OP's code does not either and so stops the scan. Since OP's code did not consume the '\n' and scanf() did not return 1 (which OP's code failed to test), following unposted code certainly fell into undefined behavior.
My guess is that your program runs, but the console closes before you can see the result.
Try to modify to the following:
char *text;
text = malloc(256);
printf("Enter a sentence:");
scanf("%[^\n]s", text);
printf("%s",text);
system("pause");
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
Why the following code is getting terminated after one round if the getchar() in the 5th line is not used?
char s;
while(1){
printf("Enter two integers: ");
scanf("%d%d",&a,&b);
getchar();
c = a + b;
printf("Addition of %d & %d is %d\n",a,b,c);
printf("Add more numbers(yes/no): ");
scanf("%c",&s);
if(s == 'y')
continue;
else
break;
}
And why using string is not working in the following code? I have included the <string.h> file.
char s[10];
while(1){
printf("Enter two integers: ");
scanf("%d%d",&a,&b);
getchar();
c = a + b;
printf("Addition of %d & %d is %d\n",a,b,c);
printf("Add more numbers(yes/no): ");
scanf("%s",s);
if(s == "yes")
continue;
else
break;
}
When you enter the input for the first scanf("%d%d",&a,&b) then you probably ended that with the Enter key.
That Enter key is added as a newline into the input buffer that scanf reads from.
If you don't have the getchar() call then that newline is what the next scanf("%c",&s) will read.
One solution is, as you've noted, to use getchar() to read and throw away the newline. Another solution is to ask scanf to do the same:
scanf(" %c",&s);
// ^
// Note the space here!
The leading space tells scanf to skip and ignore all leading white-space character, of which newline is one such character.
Note that most format specifiers for scanf automatically skip and ignore leading white-space. For example %s will do that, which means your second version with scanf("%s",s) doesn't need the getchar() call.
Also note that this should have been easily deduced by spending five minutes in a debugger to step through the code statement by statement while monitoring variables and their values.
Then for s == "yes". What happens here is that the array s will decay to a pointer to its first element, as will the literal string, and then you compare these pointers to see if they are the same, which they will most likely never be.
It's somewhat simplified equivalent to this:
char yes_literal[4] = "yes";
if (&s[0] == &yes_literal[0]) ...
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
How can enter two strings with scanf in C?, I want to use them as follow:
#include <stdio.h>
#include <string.h>
main()
{
char kid[25];
char color[10];
scanf( "%24[^\n]", kid); // kid name
scanf( "%9[^\n]", color);
printf("%s\'s favorite color is %s.\n", kid, color);
return 0;
}
You are reading input till a \n into kid with the first scanf(). But that scanf() won't read the \n and it will remain in the input buffer.
When the next scanf() is done, the first character it sees is the \n upon which it stops reading before anything is written to color.
You could do
scanf("%24[^\n] ", kid);
scanf("%9[^\n]", color);
The space after the [^\n] will read a white-space character like \n.
If %*c is used like
scanf("%24[^\n]%*c", kid);
%*c in scanf() will cause a character to be read but it won't be assigned anywhere. * is the assignment suppressing character. See here.
But if exactly 25 characters are given as input before a \n, the %*c will just read the last character leaving the \n still in the input buffer.
If you can use a function other than scanf(), fgets() would do well.
Do
fgets(kid, sizeof(kid), stdin);
but remember that fgets() would read the \n as well into kid. You could remove it like
kid[strlen(kid)-1]='\0';
Due to this \n being read, the number characters that are read will be effectively 1 less.
Your problem is that this line does not read the \n character from the stream.
scanf( "%24[^\n]", kid); // kid name
So you read the kids name but don't remove the newline character. So the next scanf() just sees a return character on the input stream and thus you will get an empty color.
if (scanf( "%24[^\n]", kid) == 1) { // kid name
char term;
while ( scanf( "%c", &term) == 1 && term != '\n') {
/* read characters until you can't read or you reach the end of line */
}
}
else {
/* Error */
}
If the user input a kids name longer than 24 characters then you need to read and throw away these characters (or do some appropriate error handling). The end of the kids name is marked by the '\n' character.
Note: The while loop above is for illustration purposes. There are better way.
if (scanf( "%24[^\n]", kid) == 1) { // kid name
scanf("%*[^\n]"); // Note. You can not use "%*[^\n]\n". This will fail if just a newline
scanf("\n"); // So split into two lines (the first may read nothing).
}
else {
/* Error */
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I have a code written in c:
int num1,num2;
while(1)
{
scanf("%d",&num1);
scanf("%d",&num2);
}
I want to break out of this loop when input is not given when the program runs.
You asked, and that is much, much more than I normally see.
Try the following:
int num1, num2;
while (1) {
if (scanf(" %d %d", &num1, &num2) != 2) {
/* End of input (Ctrl+D)? */
if (feof(stdin))
break;
/* No, just invalid input. */
fprintf(stderr, "That was not two integer numbers. I'm out.\n");
break;
}
printf("You supplied %d and %d.\n", num1, num2);
}
You see, the scanf family of functions returns the number of successful conversions. Above, if scanf() does not read and convert two integers, we check if it failed because it encountered end of input (if it did, then feof(stdin) is true). Otherwise, it must have failed because the input was something else. We cannot retry, because the unparseable input is still unread -- the next try would just fail the same way. (There are ways to consume the bad input, but I'd just read the input line-by-line, and try and parse (or reject) each line instead.)
I see so much code that never checks the return value of any of the scanf family of functions, and so many questions on the behaviour caused by it (incorrect input causing endless loops, maybe out of memory situations, buffer overruns), that it sometimes feels futile to even read a question related to any scanf() function. But, you asked. (And, the other you, reading this question and answer but not being the OP, are interested in the matter.) That is good. That means, perhaps someone actually cares about writing robust programs that don't get into a hissy panic whenever the input diverges just a bit from the expected. I want robust programs.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
program source codeHow should I use fflush in C on OS/X? When I use it, it does not clear my buffer and terminates the program straight away.
Calling fflush(stdin); invokes undefined behavior. You should not use this to flush characters from the standard input buffer. Instead, you can read the characters upto the next linefeed and ignore them:
int c;
while ((c = getchar()) != EOF && c != '\n')
continue;
You can also use scanf() for this, but it is tricky:
scanf("%*^[\n]"); // read and discard any characters different from \n
scanf("%*c"); // read and discard the next char, which, if present, is a \n
Note that you cannot combine the 2 calls above because it would fail to read a linefeed non preceded by any other characters, as the first format would fail.