I'm just starting to learn C and I'm having problem with stopping my program based on what the user inputted.
#include <stdio.h>
#include <stdbool.h>
int main()
{
int a;
int b;
char c[5];
printf("Enter the two values you like to compare, type stop to end.\n");
while (c != "stop")
{
scanf_s(" %d %d %s", &a, &b, &c);
if (!(a^b))
{
printf("both are equal\n");
getchar();
}
else
{
printf("both are not equal\n");
getchar();
}
}
printf("Thanks for playing.");
getchar();
return 0;
}
The problem that I'm having is having to put in another variable, c, in my scanf_s. How would I do it so that the user does not have to put in another word after the 2 numbers? Also how can I check if the user only input "stop" so that it will stop the program? Btw the way I have it right now also does not stop the program when I do "10 10 stop". Thanks.
remove & for c in scanf_s(" %d %d %s", &a, &b, &c);
use strcmp to compare strings.
if you need to ignore case while comparing use strcasecmp (for UNIX based systems) and stricmp (for windows).
Use do-while instead of while if you need to run the loop at least once.
Full Working Code:
#include <stdio.h>
#include <string.h>
int main()
{
int a;
int b;
char c[5] = {'\0'};
do {
printf("Enter the two values you like to compare, type stop to end.\n");
scanf("%d%d%s", &a, &b, c);
if (!(a^b))
{
printf("both are equal\n");
getchar();
}
else
{
printf("both are not equal\n");
getchar();
}
}
while (strcmp(c,"stop"));
printf("Thanks for playing.");
getchar();
return 0;
}
while (c != "stop")
You cannot compare strings in C like that, use memcmp() or strncmp() library functions available in string.h. Read about them to know how they can be implemented as condition in while loop.
Also, to get string input, use
scanf_s(" %d %d %s", &a, &b, c); // Remove that litle '&' before 'c'.
NOTE: The function scanf_s returns the number of inputs scanned correctly, you should check that before proceeding with input values.
To get the user to stop without explicitly entering "stop", many ways are there:
1) Use do-while loop and keep asking user if he wants to play more.
2) Use negative numbers input (say -1) to quit.
Use line below to make sure your 'c' scan your string entered.
scanf(" %d %d %s", &a, &b, c);
Edit:
Consider replacing your while with line below to make sure you stop works. Include "string.h"
while (strcmp(c,"stop"))
Here is the fixed version... I have add the comments in the code for understanding...
#include <stdio.h>
#include <string.h>
int main()
{
int a;
int b;
char c[5] = {'\0'};
printf("Enter the two values you like to compare, type stop to end.\n");
while (strcmp(c,"stop"))
{
scanf("%d%d%s", &a, &b, c);
if (!(a^b))
{
printf("both are equal\n");
getchar();
}
else
{
printf("both are not equal\n");
getchar();
}
}
printf("Thanks for playing.");
getchar();
return 0;
}
First, lets correct your program:
&c (third argument to scanf_s) is incorrect. It should be c (because it is already a pointer). According to docs, scanf_s requires sizes to be specified for all %s format strings; therefore, the way you are doing things now, you should have written scanf_s(" %d %d %4s", &a, &b, c);
The program would be much easier to use if you changed your logic to "enter a blank line to exit". You can test this looking at the return value of scanf_s, which will be the number of format strings correctly read from the input.
If you need to ask for strings, then allow either, and look at whatever the user wrote to see whether it was number or string:
#include <stdio.h>
#include <string.h>
int main() {
int a;
int b;
char c[32];
printf("Enter the two values to compare, or type stop to end.\n");
while (fgets(c, 31, stdin) != NULL && strncmp("stop\n", c)) != 0) {
// user did not request to exit and wrote something; maybe 2 numbers
if (sscanf(c, "%d %d", &a, &b) != 2) {
// but he did not write two numbers. Complain and repeat.
printf("please write two numbers to compare, or type stop to end.\n");
continue;
}
if (a == b) {
printf("both are equal\n");
} else {
printf("both are not equal\n");
}
}
printf("Thanks for playing.\n");
return 0;
}
fgets reads whole lines, and you can then try to parse them using sscanf. This has the advantage over common scanf that you can try to parse the same line in different ways, depending on what you find in it. Generally, you do not want to fill your code with getchar(). If you are debugging, your debugger will stop for you. If you are not debugging, you will want to test or use your program with input redirection, and getchar() is simply not needed.
Its because you are using &c instead of just c in scanf_s. Replace that and it should work. Also, c is a string, so, you have to use strcmp instead of !=.
An easier way to write this code would be::
int main()
{
int a;
int b;
char c;
do
{
printf("Would you like to play?\nPress 'Y' for 'Yes' or 'N' for 'No'\n");
scanf( "%c", &c ) ;
/*scanf_s( "%c", &c, 1 ) ; */
if( c != 'Y' && c != 'y' )
break ;
printf("Enter the two values you like to compare\n" ) ;
scanf(" %d %d", &a, &b);
if (!(a^b))
{
printf("both are equal\n");
getchar();
}
else
{
printf("both are not equal\n");
getchar();
}
}while(1) ;
printf("Thanks for playing.");
getchar();
return 0;
}
Related
Every time I run the program, the last "if" statement is not working, it means if I type "no", the loop won't break. Can someone please help me here?
#include <stdio.h>
int main() {
int age, i;
char ans;
for (i = 0; i < 3; i++) {
printf("\n enter your age:");
scanf("%d", &age);
if (age > 18) {
printf("your age is %d, you are allowed to enter", age);
} else if (age == 18) {
printf("I don't know what to do with you");
} else {
printf("your age is %d, you are not allowed to go in", age);
}
printf("\n continue?");
scanf(" %c", &ans);
if (ans == 'no') { // <-- here
break;
} else {
continue;
}
}
return 0;
}
use if (ans == 'n'). If you want to use the word "no", you have to change the type of variable ans to char array and use strcmp() method to compare strings.
In c programming single quotes (i.e. 'c') are used for characters and double quotes (i.e. "c") are used for strings. In double quotes last character is NULL.
Note: We cannot keep two characters in single quote like 'no'.
In your case first thing, declare ans as character array(i.e. string).
char ans[SIZE_AS_PER_REQUIREMENT];
To take input in this,
scanf("%s",ans);
For a better user experience before taking input give a proper message to user.
printf("\n Do you want to continue(yes/no)?");
Now to compare user's answer with program's condition, We have C-Language string library (i.e. string.h), include this before using any C-language inbuilt String function.
#include <string.h>
and use any of string function strcmp or stricmp as per requirement. Here I am going to use stricmp because it is possible that user may enter "no"/"No"/"NO". stricmp ignore the case.
stricmp(string1,string2)
It returns
Negative Number if string1 is less than string2
Zero if string1 equivalent to string2
Positive Number if string1 is greater than string2
So, for our case we check for Zero.
See the below program, I just added these in your code.
#include <stdio.h>
#include <string.h>
int main() {
int age, i;
char ans[5];//declare ans as character array
for (i = 0; i < 3; i++) {
printf("\n enter your age:");
scanf("%d", &age);
if (age > 18) {
printf("your age is %d, you are allowed to enter", age);
} else if (age == 18) {
printf("I don't know what to do with you");
} else {
printf("your age is %d, you are not allowed to go in", age);
}
printf("\n Do you want to continue(yes/no)?");
scanf("%s",ans);//take input as string in ans, its character array
if (stricmp(ans,"no") == 0) { // 0 means both are equal
break;
} else {
continue;
}
}
return 0;
}
You used %c which is for characters.
Instead, use %s.
So in my class, part of the homework assignment is to have a function that will return a character that's been entered.
I tried to create this sample code, but it's not working as I hoped.
#include <stdio.h>
char readCharacter();
int main(){
char x;
x = readCharacter();
printf("You inputted %c", x);
return 0;
}
char readCharacter(){
char z;
printf("Input character\n");
scanf("% c", &z);
return z;
}
I enter a character, I decided to type w, and the program told me the character was some weird funky font.
The actual code from my homework, or rather a snippet from it, is
#include <stdio.h> // needed by printf, scanf()
#include <ctype.h> // needed by tolower()
#include <stdlib.h> // for exit()
double readNumber(char *prompt) {
double val;
printf("%s", prompt);
scanf("% lf", &val);
//if input is not a number, exit program
if (scanf("%lf", &val) != 1) {
printf("Invalid input.\n");
exit(1);
}
return val;
}
char readYesOrNo(char* prompt) {
char yn;
printf("%s\n", prompt);
scanf("% c", &yn);
return yn;
}
int main() {
double bonus;
char yesNo;
yesNo = readYesOrNo("Did the worker get a bonus ? (y/n) ");
if (yesNo == 'y' || yesNo == 'Y') {
bonus = readNumber("Enter bonus: ");
}
else {
bonus = 0;
}
return 0;
}
In the actual homework code, the readYesOrNo function doesn't even wait for me to input anything, it just displays the prompt asking for a y/n response, then goes on to the next line of code, not waiting for user input and assuming a no response.
I have no clue why this isn't working.
% c is not a valid format specifier. But %c is probably what you meant.
This line:
scanf("% c", &z);
Needs to be this:
scanf("%c", &z);
This question already has answers here:
Check if input is float else stop
(6 answers)
Closed 7 years ago.
So, I'm creating a program that calculates the area of a triangle, and I need it to tell the user if he typed a letter or a negative number, in order, I created the code:
I need to use isdigit
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <ctype.h>
int main () {
float a, b, c;
float s=0, ar1=0, ar2=0;
printf("Inform the value of side A.");
fflush(stdin);
scanf("%f",&a);
while(a<=0||isdigit((int)a)){
printf("Invalid value.");
fflush(stdin);
scanf("%f",&a);
}printf("Inform the value of side B.");
fflush(stdin);
scanf("%f",&b);
while(b<=0||isdigit((int)a)){
printf("Invalid value.");
fflush(stdin);
scanf("%f",&b);
}printf("Inform the value of side C.");
fflush(stdin);
scanf("%f",&c);
while(c<=0||isdigit((int)a)){
printf("Invalid value.");
fflush(stdin);
scanf("%f",&c);}
s=((a+b+c)/2);
ar1=(s*(s-a)*(s-b)*(s-c));
ar2=pow(ar1,0.5);
printf("The semiperimeter is %f",s);
printf("The area of the triangle is%f",ar2);
system ("pause");
return 1;
}
But, when I compile/run it, and type "x", or "blabla" when I was supposed to type a number, nothing happens, and the program doesn't warn me, what should I do?
First of all, using fflush on stdin is Undefined Behavior as per the C11 standard, although it is well defined on some implementations.
Secondly, you can't use simply use isdigit that way. Once %f sees invalid data such as characters, the scanf terminates and the corresponding argument is left untouched. Also, using isdigit on an uninitialized variable leads to Undefined Behavior.
What you can do is check the return value of scanf. All the three scanfs in your code returns 1 if successful.
Fixed Code:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <ctype.h> //Unused header
void flushstdin() //Removes all characters from stdin
{
int c;
while((c = getchar()) != '\n' && c != EOF); //Scan and discard everything until a newline character or EOF
}
int main () {
float a, b, c;
float s=0, ar1=0, ar2=0;
printf("Inform the value of side A\n");
//fflush(stdin); Avoid this to make your code portable
while(scanf("%f",&a) != 1 || a <= 0){
printf("Invalid value\n");
flushstdin(); //Alternative way to flush stdin
}
printf("Inform the value of side B\n");
//fflush(stdin);
while(scanf("%f",&b) != 1 || b <= 0){
printf("Invalid value\n");
flushstdin(); //Alternative way to flush stdin
}
printf("Inform the value of side C\n");
//fflush(stdin);
while(scanf("%f",&c) != 1 || c <= 0){
printf("Invalid value\n");
flushstdin(); //Alternative way to flush stdin
}
s=((a+b+c)/2);
ar1=(s*(s-a)*(s-b)*(s-c));
ar2=pow(ar1,0.5);
printf("The semiperimeter is %f\n", s);
printf("The area of the triangle is %f\n", ar2);
system ("pause");
return 0; // 0 is usually returned for successful termination
}
Also, it is better to add newline characters at the end of the strings in printf as seen in the above program. They
Improve readability
Flushes the stdout
I'm trying to write a basic calculator program in C, and I'm almost there! I have one issue though, and it's concerning repeatedly querying the user for input.
I can get through my loop once, but even though the user inputs the correct character, my program still breaks out of the loop.
I'm fairly new to C, but I've done a decent amount of programming in Java, so I understand the functionality of loops, conditionals, and data types.
#include <stdio.h>
int main()
{
char yes;
int a, b, c, choice;
yes = 'y';
while(yes == 'y' || yes == 'Y')
{
printf("Enter first integer: ");
scanf("%d", &a);
printf("Enter second integer: ");
scanf("%d", &b);
printf("\nAdd(1), Subtract(2), Multiply(3), Divide(4): ");
scanf("%d", &choice);
printf("\n");
switch(choice)
{
case(1):
c = a + b;
printf("%d + %d = %d\n", a, b, c);
break;
case(2):
c = a - b;
printf("%d - %d = %d\n", a, b, c);
break;
case(3):
c = a * b;
printf("%d * %d = %d\n", a, b, c);
break;
case(4):
c = a / (float)b;
printf("%d / %d = %d\n", a, b, c);
break;
default:
printf("Incorrect choice. Try again.\n");
}
printf("\nAgain (Y/N): ");
scanf("%c", &yes);
}
return 0;
}
You need to consume the trailling newline, enter remains in the stdin buffer ready to be read by the next scanf.
Change
scanf("%c", &yes);
to
scanf(" %c", &yes);
The problem is that the newline character is left on the input after inputting a number to choose what operation to do. So when the user is asked if they want to do it again, the newline is taken instead of the y or n. I might be wrong, it's been a while since I've done some programming.
What worked for me to fix it was to put a little bit of code after the line
printf("\nAgain (Y/N): ");
Adding this bit right after the printf statement will remove the newline from the input and should do the trick.
while(getchar() != '\n')
getchar();
Maybe someone else can explain exactly why this works, I don't remember the specifics. It's a little thing that I found useful to remember, it comes up every now and again.
In the program written below how i can ensure that only integer value is entered?
And if character is entered the program should convert it to its ASCII equivalent and then add them and show output as number.
Please help me......
#include<stdio.h>
int main(int argc, char **argv)
{
int a,b,c;
printf("enter two numbers:-");
scanf("%d \t %d",&a,&b);
c=a+b;
printf("addition of numbers= %d",c);
}
scanf returns the number of items that it successfully read, so you can check to make sure that it returns the same number that you expect. For example,
if (scanf("%d \t %d", &a, &b) != 2)
{
// handle error
}
Note that \t is a whitespace character, and whitespace is ignored by scanf.
Just to add to what James said.
Dont forget to flush stdin
#include<stdio.h>
int main(int argc, char **argv)
{
int a,b,c;
printf("enter two numbers:-");
if( scanf("%d \t %d",&a,&b) == 2 )
{
c=a+b;
printf("addition of numbers= %d",c);
}
else {
printf("please enter a valid input");
getchar(); // the getchar will clear the stdin otherwise next time you go do
// a scanf it might not work.
}
}