The problem is that when i type any character except for y or n it display this message two times instead to one)
This program is 'Calculator'
Do you want to continue?
Type 'y' for yes or 'n' for no
invalid input
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void main ()
{
//program
//first to get two numbers
//second to get choice
int x=0,y=0,n=0;
char choice;
//clrscr(); does no work in devc++
system("cls"); //you may also use system("clear");
while(x==0)
{
puts("\t\tThis program is 'Calculator'\n\n");
puts("Do you want to continue?");
puts("Type 'y' for yes or 'n' for no ");
scanf("%c",&choice);
x++;
if(choice=='y')
{
y++;
puts("if this worked then we would continue to calculate the 2 no");
}
else if(choice=='n')
exit(0);
else
{
puts("invalid input");
x=0;
}
}
getch();
}
`
it looping twice because enter(\n) character is stored in buffer use scanf like this(add space before %c)
scanf(" %c",&choice);
That is because of the trailing new line after you enter y or n and hit enter key.
Try this out:
scanf("%c",&choice);
while(getchar()!='\n'); // Eats up the trailing newlines
If you input any character other than 'y' or 'n', control enters the :
else
{
puts("invalid input");
x=0;
}
block, which resets x to 0, Now the loop condition :
while(x == 0)
is true and hence it enters the loop again.
Also you may want to skip the trailing newline character while reading like :
scanf(" %c", &choice );
Related
I made a simple (and ugly) program to check the password that user inputs for uppercase, lowercase, number and the dollar sign. the problem is that my printf in the beginning of my do while loop repeats itself awkwardly while the scanf doesn't even stop it, and that repetition depends on the input of the user. i put some comments to explain the code, and i'll do some screen shots to show you what i mean by printf repeating itself.
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include<string.h>
#include<ctype.h>
int main(){
char pass[10];
int i,t,x,y,z;
t=y=z=0;
do{
printf("Enter a password it needs to have an uppercase letter a lowercase one, a number and a $ sign: ");
scanf(" %c", pass);
//here i test for upper case, letter by letter
for(i=0;i<10;i++){
if(isalpha(pass[i])){
if(isupper(pass[i])){
t++;
}
}
}
//here i test for lower case, letter by letter
for(i=0;i<10;i++){
if(isalpha(pass[i])){
if(islower(pass[i])){
y++;
}
}
}
//here i test for number, letter by letter
for(i=0;i<10;i++){
if(isdigit(pass[i])){
z++;
}
}
//here i look for the dollar sign
for(i=0;i<10;i++){
if(pass[i]=='$'){
x++;
}
}
printf("\n");
//if all the tests were true the variables t,x,y and z would not be 0
}while(t==0 || x==0 || y==0 || z==0);
}
the first display of the code works fine:
enter image description here
however as you will see in this picture, when i enter a bad password the printf repeats:
enter image description here
and the repeating of printf depends on how much the user enters:
enter image description here
even when i enter a good password, the printf repeats itself a bunch of times before the code ends:
enter image description here
i assume the problem is with the for loops in bedded in the do while loop, but i just can't find where exactly is the problem and why printf repeats so weirdly
The main issue is with:
scanf(" %c", pass);
This tries to scan in a single char. To scan in a string use:
scanf("%9s", pass);
The 9 puts a limit on how many chars can be inputted to avoid overflow. 10 is not used because you need to leave room for the end-of-string marker ('\0').
Some other improvements:
do{
// Move here to reset each time
t = y = z =0;
printf("Enter a password it needs to have an uppercase letter a lowercase one, a number and a $ sign: ");
// Should always test the result of scanf
if (1 != scanf("%9s", pass)) {
// Some error
break;
}
// Combine all the for loops
for (i = 0; pass[i]; i++) {
if (isupper(pass[i])) {
t++;
}
else if (islower(pass[i])) {
y++;
}
else if (isdigit(pass[i])) {
z++;
}
else if (pass[i] == '$'){
x++;
}
}
printf("\n");
//if all the tests were true the variables t,x,y and z would not be 0
} while (t==0 || x==0 || y==0 || z==0);
I am new to C programming. I wrote a simple switch case but it is not executing as expected . Can some one tell me what is wrong here??
#include <stdio.h>
int main() {
int i;
char yes;
bool flag = true;
while(flag) {
printf("Enter the value");
scanf("%d",&i);
switch(i) {
case 1:
printf("Hi");
break;
case 2:
printf("Hello");
break;
}
printf("Enter Y or N to continue");
scanf("%c",&yes);
if (yes == 'N') {
flag = false;
}
}
return 0;
}
The result I am expecting is:
Enter the Value
1
Hi
Enter Y or N to continue
Y
Enter the Value
2
Hello
Enter Y or N to continue
N
But the result I am getting is :
Enter the value 1
HiEnter Y or N to continueEnter the value N
HiEnter Y or N to continue
When you hit Enter after typing in the first number, scanf read all numeric characters from the input stream except the newline character produced by that Enter hit. The newline character is not a part of the number. It is left in the input stream, unread, waiting for someone else to read it.
The next scanf("%c",&yes); discovered that pending newline charcter and it read it without waiting. The %c format specifier does not skip whitespace in the input, it just reads the first character it sees.
Replace your scanf with
scanf(" %c",&yes);
to make it skip whitespace. That way it will ignore that pending newline and actually wait for you to enter something.
In all your printf you need to add \n at the end.
For example on usage, see here: printf
This should work for you:
(You forgot all '\n' in your printf statements and add a space in your char scanf statements)
#include <stdio.h>
int main() {
int i;
char yes;
int flag = 1;
while(flag) {
printf("Enter the value\n");
scanf("%d",&i);
switch(i){
case 1:
printf("Hi\n");
break;
case 2:
printf("Hello\n");
break;
}
printf("Enter Y or N to continue\n");
scanf(" %c", &yes);
if (yes == 'N')
flag = 0;
}
return 0;
}
Output:
Enter the Value
1
Hi
Enter Y or N to continue
Y
Enter the Value
2
Hello
Enter Y or N to continue
N
It's not a problem with the switch statement. It's a problem with your output - there aren't line breaks ('\n'). For example, instead of printf("Hi"); you might want to have printf("Hi\n");, which adds a line space at the end.
I am writing a piece of code and in one part of my code I am using a switch statement in C language. if I press n it exits correctly if I press y it will infinite loop the default statement until I press control c. what am I doing wrong here. been changing the while statement but can't find the right one.
int main()
{
char ans;
printf("DO you want to continue?");
scanf("%c", &ans);
do
{
switch(ans)
{
case 'y':
some stuff...
printf("DO you want to continue?");
scanf("%c", &ans);
break;
case'n':
printf("BYE");
break;
default:
printf("error, you must enter y or n");
continue;
}
}
while (ans!='n');
return 0;
}
When you press enter, the linefeed character \n is added to the input stream. Your code does not anticipate this, because switch(ans) only handles y, n or “everything else” (which includes the linefeed character).
To fix this, allow scanf to ignore any preceding whitespace by changing your format string to " %c" instead, e.g.
scanf(" %c", &ans);
// ^ space character inserted here
I think it would make more sense to move the scanf call to inside the loop, like this:
int main()
{
char ans;
do
{
printf("DO you want to continue?");
if (scanf(" %c", &ans) != 1)
break;
switch(ans)
{
case 'y':
// some stuff...
break;
case 'n':
printf("BYE");
break;
default:
printf("error, you must enter y or n");
continue;
}
}
while (ans!='n');
}
Don't forget to always check the result of scanf(). It will return the number of items successfully scanned (in your case, you want it to return 1). If it returns 0 or a negative number, then another problem has occurred.
New to C still learning.
The program should start the first time with out needing to be asked to do anything. Then it prompts the user to continue with a "Y/N". I keep errors could anyone tell me why it doesn't work I don't know what to do with the errors that I get from it.
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <ctype.h>
void theQnA(char charIn);
int main(void)
{
int answerint = 0;
char charIn;
char anwser;
printf("Enter a character to be examined: ");
scanf("%c", &charIn);
theQnA(charIn);
while (answerint == 0)
{
printf("Would you like to run it again? Y/N\n");
scanf("%c", &anwser);
if (anwser == 'y')
{
printf("Enter in another character buddy\n");
scanf("%c", &charIn);
theQnA(charIn);
}
else (anwser != 'y')
{
answerint = (answerint--);
}
}
printf("Goodbye\n");
return 0;
}
void theQnA(char charIn)
{
if (islower(charIn))
printf("You have entered in a lower case letter dude\n");
else if (isdigit(charIn))
printf("You enterd in a num man\n");
else if (isupper(charIn))
printf("Its upper case man\n");
else if (ispunct(charIn))
printf("You entered in a punctuation!\n");
else if (isspace(charIn))
printf("You enterd in a whitespace dude\n");
else
printf("control char/n");
return;
}
You have else (anwser != 'y'). It should be else if (anwser != 'y'), or better yet just else. The prompt Would you like to run it again? Y/N will also be printed twice because of how your loop is structured. You have quite a few mistakes, but here's some advice on your loop.
You can use your anwser variable in your while condition. answerint is unnecessary. Also, when you type a character and press enter, scanf (with %c) will extract the character but leave the newline in the buffer. That means the next call to scanf will return a newline, which will make it appear as if your program is skipping your input statements. To fix this, add a space before the %c in your call:
scanf(" %c", &charIn);
Your logic was also a bit out of place. Look at how this example is structured.
printf("Enter a character to be examined: ");
scanf(" %c", &charIn);
theQnA(charIn);
printf("Would you like to run it again? y/n\n");
scanf(" %c", &anwser);
while (anwser == 'y')
{
printf("Enter in another character buddy: ");
scanf(" %c", &charIn);
theQnA(charIn);
printf("Would you like to run it again? y/n\n");
scanf(" %c", &anwser);
}
This program runs into an infinite loop despite providing 'n' as an input,to exit the while loop.
What could be the issue ?
#include<stdio.h>
main()
{
int num,p=0,q=0,r=0;
char check='y';
while(check!='n')
{
printf("do you want to enter a number y or n");
scanf("%c",&check);
getchar();
printf("enter a number");
scanf("%d",&num);
if(num>0)
p++;
else if(num<0)
q++;
else
r++;
}
printf("positive=%d\t negative=%d\t zero=%d\t",p,q,r);
}
while(check!='n')
{
printf("do you want to enter a number y or n");
scanf("%c",&check);
getchar();
printf("enter a number");
scanf("%d",&num);
The scanf("%d", &num); leaves the newline in the input buffer, thus in the next iteration of the loop, that is stored in check. After that, the getchar() consumes the 'n' or 'y' you entered. Then the scanf("%d", &num); skips the newline left in the buffer, scans the entered number, and leaves the newline in the buffer. You need to remove the newline between scanning in the number and querying whether you want a next iteration.
Above that, it would be better to exit the loop immediately after the user entered an 'n', so
while(check!='n')
{
printf("do you want to enter a number y or n");
scanf("%c",&check);
if (check == 'n') {
break;
}
printf("enter a number");
scanf("%d",&num);
getchar(); // consume newline
would be better. That would still be open to bad things should the user input not match expectations, so if you want a robust programme, you need to check the return value of scanf to know whether the conversion was successful, and completely empty the input buffer before and after scanning in the number.
The issue is that the loop isn't exiting until the while condition is re-evaluated at the top of the loop. I'd suggest reworking your loop to something like this.
// we've purposely changed this to an infinite loop because
// we hop out on condition later
while(1)
{
printf("do you want to enter a number y or n");
scanf("%c",&check);
getchar();
// here's the code that will jump out of the loop early if the user
// entered 'n'
if('n' == check)
break;
// user didn't enter 'n'...they must want to enter a number
printf("enter a number");
scanf("%d",&num);
if(num>0)
p++;
else if(num<0)
q++;
else
r++;
}
You are not checking the character input. Here is what it should be:
printf("do you want to enter a number y or n");
scanf("%c",&check);
/* This is what you need to add */
if (check == 'y') {
getchar();
printf("enter a number");
scanf("%d",&num);
}