I am writing a simple quiz in C (using CodeBlocks 13.12)
It compiles, but doesn't work in second question. Whatever I will input, it always give answer 'that's sad'.
I can't understand what is wrong.
I came to this, where if I comment line 13 ( scanf("%d", &age); ) it's starting works ok for second question.
What the problem is?
#include <iostream>
#include <stdio.h>
#include <windows.h>
#include <clocale>
int main()
{
int age;
char S1;
printf("How old is your dog? \n");
scanf("%d", &age);
if (age <= 7)
{
printf(" very young. the end \n");
return 0;
}
else
{
printf("old dog. \n \n");
}
//question2
printf("Do you like dogs? y/n \n");
scanf("%c%c", &S1);
if (S1 == 'y')
{
printf("hey, that's nice \n");
}
else
{
printf(" that's sad :( . \n");
return 0;
}
return 0;
}
You cause undefined behavior by
scanf("%c%c", &S1);
scanf reads two chars, one stored in S1, one stored in some location on the stack because scanf expects a second char* to be supplied.
If your intention is to ignore the newline following the actual character, write
scanf("%c%*c", &S1);
Change the second scanf() to
scanf(" %c", &S1);
This would escape the left out newline character \n in the input buffer.
Plus, you are reading one char in this. So you need only one %c
scanf("%c", &S1);
is the correct way to input one character ,
Related
I have an assignment in C language that requires to ask users to enter values to arrays. My idea is createing two different arrays which one contains integer values and the other holds character values. This is my code so far:
#include <stdio.h>
int main()
{
char continued;
int i = 0;
char instrType[10];
int time[10];
printf("\nL-lock a resource");
printf("\nU-unlock a resource");
printf("\nC-compute");
printf("\nPlease Enter The Instruction Type");
printf(" and Time Input:");
scanf("%c", &instrType[0]);
scanf("%d", &time[0]);
printf("\nContinue? (Y/N) ");
scanf("%s", &continued);
i = i + 1;
while (continued == 'Y' || continued == 'y')
{
printf("\nL-lock a resource");
printf("\nU-unlock a resource");
printf("\nC-compute");
printf("\nPlease Enter The Instruction Type ");
printf("Time Input:");
scanf("%c", &instrType[i]);
scanf("%d", &time[i]);
printf("\nContinue? (Y/N) ");
scanf("%s", &continued);
i = i + 1;
}
return 0;
}
The expected value should be: L1 L2 C3 U1
My Screenshot
The loop just stopped when I tried to enter new values and the condition did not check the value even I entered 'Y' meaning 'yes to continue' please help :(
You are comparing a string with a character that is instead of using scanf("%s",&continued) try using "%c"
The main problem is scanf("%c", &char) because scanf() after had read the input print a \n to pass at the next line, this cause that the next scanf() instead of reading your input, go to read \n, causing the failure in the reading of the input.
To avoid this problem put a space before %c ==> scanf(" %c", &char)
#include <stdio.h>
int main()
{
char continued;
int i = 0;
char instrType[10];
int time[10];
do
{
printf("L-lock a resource\n");
printf("U-unlock a resource\n");
printf("C-compute\n");
printf("Please Enter The Instruction Type and Time Input: ");
scanf(" %c%d", &instrType[i], &time[i]);
printf("Continue? (Y/N) ");
scanf(" %c", &continued);
i++;
} while (continued == 'Y' || continued == 'y');
return 0;
}
Other things:
Instead of i = i + 1 you can use i++
Instead of using a while() is better using a do{...}while() for saving some line of code.
You can concatenate more inputs in a single line ==> scanf(" %c%d", &instrType[i], &time[i])
I'm pretty new to C, and I have a problem with inputing data to the program.
My code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
int a;
char b[20];
printf("Input your ID: ");
scanf("%d", &a);
printf("Input your name: ");
gets(b);
printf("---------");
printf("Name: %s", b);
system("pause");
return 0;
}
It allows to input ID, but it just skips the rest of the input. If I change the order like this:
printf("Input your name: ");
gets(b);
printf("Input your ID: ");
scanf("%d", &a);
It will work. Although, I CANNOT change order and I need it just as-is. Can someone help me ? Maybe I need to use some other functions. Thanks!
Try:
scanf("%d\n", &a);
gets only reads the '\n' that scanf leaves in. Also, you should use fgets not gets: http://www.cplusplus.com/reference/clibrary/cstdio/fgets/ to avoid possible buffer overflows.
Edit:
if the above doesn't work, try:
...
scanf("%d", &a);
getc(stdin);
...
scanf doesn't consume the newline and is thus a natural enemy of fgets. Don't put them together without a good hack. Both of these options will work:
// Option 1 - eat the newline
scanf("%d", &a);
getchar(); // reads the newline character
// Option 2 - use fgets, then scan what was read
char tmp[50];
fgets(tmp, 50, stdin);
sscanf(tmp, "%d", &a);
// note that you might have read too many characters at this point and
// must interprete them, too
scanf will not consume \n so it will be taken by the gets which follows the scanf. flush the input stream after scanf like this.
#include <stdlib.h>
#include <string.h>
int main(void) {
int a;
char b[20];
printf("Input your ID: ");
scanf("%d", &a);
fflush(stdin);
printf("Input your name: ");
gets(b);
printf("---------");
printf("Name: %s", b);
system("pause");
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
int a;
char b[20];
printf("Input your ID: ");
scanf("%d", &a);
getchar();
printf("Input your name: ");
gets(b);
printf("---------");
printf("Name: %s", b);
return 0;
}
Note:
If you use the scanf first and the fgets second, it will give problem only. It will not read the second character for the gets function.
If you press enter, after give the input for scanf, that enter character will be consider as a input f or fgets.
you should do this way.
fgetc(stdin);
scanf("%c",&c);
if(c!='y')
{
break;
}
fgetc(stdin);
to read input from scanf after reading through gets.
scanf("%d", &a); can't read the return, because %d accepts only decimal integer. So you add a \n at the beginning of the next scanf to ignore the last \n inside the buffer.
Then, scanf("\n%s", b); now can reads the string without problem, but scanf stops to read when find a white space. So, change the %s to %[^\n]. It means: "read everthing but \n"
scanf("\n%[^\n]", b);
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
int a;
char b[20];
printf("Input your ID: ");
scanf("%d", &a);
printf("Input your name: ");
scanf("\n%[^\n]", b);
//first \n says to ignore last 'return'
//%[^\n] read until find a 'return'
printf("---------\n");
printf("Name: %s\n\n", b);
system("pause");
return 0;
}
The scanf function removes whitespace automatically before trying to parse things other than characters. %c, %n, %[] are exceptions that do not remove leading whitespace.gets is reading the newline left by previous scanf. Catch the newline usinggetchar();
scanf("%d", &a);
getchar(); // catches the newline character omitted by scanf("%d")
gets(b);
https://wpollock.com/CPlus/PrintfRef.htm
Just use 2 gets() functions
When you want to use gets() after a scanf(), you make sure that you use 2 of the gets() functions and for the above case write your code like:
int main(void) {
int a;
char b[20];
printf("Input your ID: ");
scanf("%d", &a);
//the change is here*********************
printf("Input your name: ");
gets(b);
gets(b);
//the change is here*********************
printf("---------");
printf("Name: %s", b);
system("pause");
return 0;
}
I can't understand why this does exactly what I want. The part where I used two scanf's in the loop confuses me. I compiled it using devcpp.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int dend, dsor, q, r;
char c;
while(c!='n')
{
printf("enter dividend: ");
scanf("%d", &dend);
printf("enter divisor: ");
scanf("%d", &dsor);
q=dend/dsor;
r=dend%dsor;
printf("quotient is %d\n", q);
printf("remainder is %d\n", r);
scanf("%c", &c);
printf("continue? (y/n)\n");
scanf("%c", &c);
}
system("PAUSE");
return 0;
}
FWIW, your code invokes undefined behavior. In the part
char c;
while(c!='n')
c is an uninitialized local variable with automatic storage and you're trying to use the value of c while it is indeterminate.
That said, first scanf("%c", &c); is used to eat up the newline present in the input buffer due to the press of enter key after previous input. You can read about it in details in another post.
Solve this for me because I don't really know
#include <stdio.h>
#include <stdlib.h>
int main() {
char ans;
printf("1. The patients felt _____ after taking the medicine.\n");
printf("\t a. best\n\t b. better\n\t c. good\n\n");
scanf("%c", &ans);
if (ans == 'b') {
printf("2. I ______ my essay by the time the bell rings.\n");
printf("\t a. have done\n\t b. shall do\n\t c. shall have done\n\n");
scanf("%c", &ans);
} else {
printf("YOU FAILED!");
};
return 0;
}
If you answer the first question you proceed to next and answer the 2nd question, but the problem is I can't type the answer even though there's scanf.
#include <stdio.h>
#include <stdlib.h>
int main() {
char ans;
printf("1. The patients felt _____ after taking the medicine.\n");
printf("\t a. best\n\t b. better\n\t c. good\n\n");
scanf("%c", &ans);
if (ans == 'b') {
printf("2. I ______ my essay by the time the bell rings.\n");
printf("\t a. have done\n\t b. shall do\n\t c. shall have done\n\n");
scanf(" %c", &ans);
} else {
printf("YOU FAILED!");
};
return 0;
}
The difference is:
scanf(" %c",&ans);
^ this space this will read whitespace characters (which newline also is)
until it finds a non space character.
scanf did not consume the \n character that stayed in the buffer from the first scanf call.
I try this, and it works!
The second scanf("%c"...) reads the linefeed that the first scanf left pending in standard input. You can fix this by reading an extra character this way:
#include <stdio.h>
#include <stdlib.h>
int main() {
char ans;
printf("1. The patients felt _____ after taking the medicine.\n");
printf("\t a. best\n\t b. better\n\t c. good\n\n");
scanf("%c%*c", &ans);
if (ans == 'b') {
printf("2. I ______ my essay by the time the bell rings.\n");
printf("\t a. have done\n\t b. shall do\n\t c. shall have done\n\n");
scanf("%c%*c", &ans);
} else {
printf("YOU FAILED!");
}
return 0;
}
scanf("%c%*c", &ans) reads a character and stores it into the ans variable, then it reads another character and discards it. This way the \n typed by the user after the b is discarded.
An alternative is to ignore white space characters with scanf(" %c", &ans): the in the scanf format instructs scanf to read and ignore any whitespace characters. The advantage of the first approach is that no characters are left pending after the scanf if the user entered a single character followed by enter, the second approach would leave the \n pending, but it would be ignored by the following scanf.
This question already has answers here:
scanf() leaves the newline character in the buffer
(7 answers)
Closed 4 years ago.
I want to know the reason why this code not run properly
#include<stdio.h>
main()
{
char a;
int n;
do
{
printf("enter the number");
scanf("%d",&n);
printf("the squre is %d",n*n);
printf("want any more so Y for yes N for no");
scanf("%c%[^\n]",&a);
}while(a=='Y');
}
Reasons are
1. scanf("%c%[^\n]",&a); needs two parameters. Remove %[^\n].
2. \n character left behind by the previous scanf on pressing Enter key. Next scanf will read this \n character in the buffer. You need to consume this \n. Use a space before %c specifier to eat up this \n.
Try this:
scanf(" %c",&a);
↑ A space before %c specifier
A space before %c specifier is able to eat ant number of newline characters.
Your code after modification:
#include<stdio.h>
int main(void)
{
char a;
int n;
do
{
printf("enter the number\n");
scanf("%d",&n);
printf("the squre is %d\n",n*n);
printf("want any more so Y for yes N for no\n");
scanf(" %c",&a);
}while(a=='Y');
return 0;
}
Here is a solution to your problem.
#include<stdio.h>
main()
{
char a;
int n;
do
{
printf("enter the number");
scanf("%d",&n);
a = getchar(); // <-- Here is a change.
printf("the squre is %d",n*n);
printf("want any more so Y for yes N for no");
while(a == '\n') a = getchar();
}while(a=='Y');
}
What actually is making you problem is this line.
scanf("%d",&n);
Suppose, you entered 10 then pressed 'Enter', now scanf() takes 10 and leaves a newline behind in the buffer. It is making problem. By getchar() you are eating up that new line each time after taking a input with scanf. Yes there are other solutions too with scanf() tricks but it seems simpler to me. So I shared it.
just use scanf(" %c",&a); and could be done.
Wrong code: scanf("%c%[^\n]",&a);
Right code: scanf(" %c%*[^\n]",&a);