scanf multiple variables or one variable - c

In C, I need to input four variables using scanf
scanf("%c %d %d %d", &v1, &v2, &v3, &v4)
the first variable may take two values 'c' and 'q'
when I enter c then I enter the other variables it will do some calculations but when I want to quit I should enter 'q' only and not enter the rest of the variables but scanf does not move forward until I enter the rest of the variables
is there anyway to solve it, I am not sure if it is possible using scanf but if there is another function then I don't mind using it

"is there anyway to solve it"
Read a line of user input with fgets() ...
char buf[100];
if (fgets(buf, sizeof buf, stdin)) {
.. and then scan it
char v1;
int v2,v2,v3;
int cnt = sscanf(buf, "%c %d %d %d", &v1, &v2, &v3, &v4);
if (cnt >= 1 && v1 == 'q') Quit();
else if (cnt == 4 && v1 == 'c') Do_stuff(v2,v3,v4);
else puts("Bad input");

You should use multiple scanfs for this. For example
scanf("%c", &v1);
if(v1 == 'c'){
scanf("%d %d %d",&v2, &v3, &v4);
/*some staff*/
}
else{
/*another staff*/
}

Related

How to insert a continue statement inside an if statement

My code is below. I am using C language. I want to repeat the action from the start if the user types Y but I am confused how can I make that happen.
I tried to look for a solution but the results doesn't fit for my program.
#include <stdio.h>
int main() {
int A, B;
char Y, N, C;
printf ("Enter value 1: ");
scanf ("%i", &B);
printf ("\nEnter value 2: ");
scanf ("%i", &A);
printf ("= %i", A + B);
printf ("\n\nAdd again? Y or N\n");
scanf ("%c", &C);
if (C == Y) {
//This should contain the code that will repeat the:
printf ("Enter value 1: ");
scanf ("%i", &B);
printf ("\nEnter value 2:
} else if (C == N)
printf ("PROGRAM USE ENDED.");
else
printf ("Error.");
}
You should just wrap your code inside a for loop:
#include <stdio.h>
int main() {
int A, B;
char Y = 'Y', N = 'N', C;
for (;;) { // same as while(1)
printf("Enter value 1: ");
if (scanf("%i", &B) != 1)
break;
printf("\nEnter value 2: ");
if (scanf("%i", &A) != 1)
break;
printf("%i + %i = %i\n", A, B, A + B);
printf("\n\nAdd again? Y or N\n");
// note the initial space to skip the pending newline and other whitespace
if (scanf(" %c", &C) != 1 || C != Y)
break;
}
printf("PROGRAM USE ENDED.\n");
return 0;
}
There are a lot of errors in your program.
Syntax error: please resolve it on your own.
There is no need for Y and N to be declared as character, you can use them directly as they are not storing any value.
NOW, there is no need for continue you can use while loop.
I have resolved your problem. Please take a look
Also, you are using a lot of scanf so there is an input buffer, a simple solution to it is using getchar() which consumes the enter key spaces.
#include <stdio.h>
int main()
{
int A, B;
char C = 'Y';
while (C == 'Y')
{
printf("Enter value 1: ");
scanf("%i", &B);
printf("\nEnter value 2");
scanf("%i", &A);
printf("= %i\n", A + B);
getchar();
printf("\n\nAdd again? Y or N\n");
scanf("%c", &C);
}
if (C == 'N')
{
printf("PROGRAM USE ENDED.");
}
else
{
printf("Error.");
}
}

my do-while is terminating instead of continuing my C program

When I'm trying to run without debugging the code everything runs smooth but as soon as I press Y so I can continue inputting numbers it terminates (gotta say I need help)
int main() {
int a;
char c;
do {
puts("dwse mou enan arithmo: ");
scanf_s("%d", &a);
if (a > 0) {
if (a % 2 == 0)
printf("the number %d is even \n", a);
else
printf("the number %d is odd \n", a);
} else {
printf("the program won't run with negative numbers \n");
}
printf("if you want to proceed press y or Y :");
c = getchar();
getchar();
} while (c == 'y' || c == 'Y');
return 0;
}
The character read by getchar() is the pending newline that was typed after the number but was not consumed by scanf_s.
You should consume this pending newline before reading the next character for the continuation test, which can be done easily in scanf with a space before the %c conversion specification:
#include <stdio.h>
int main() {
int a;
char c;
for (;;) {
printf("dwse mou enan arithmo: ");
if (scanf_s("%d", &a) != 1)
break;
if (a >= 0) {
if (a % 2 == 0)
printf("the number %d is even\n", a);
else
printf("the number %d is odd\n", a);
} else {
printf("the program does not accept negative numbers\n");
}
printf("if you want to proceed press y or Y: ");
if (scanf_s(" %c", &c) != 1 || (c != 'y' && c != 'Y'))
break;
}
return 0;
}

getchar following scanf (to read an integer) takes terminating "enter" key of scanf as character

When I have a scanf followed by a getchar, why does the getchar always keep getting the last delimiting character of scanf? How can I stop that? I tried looking into "format specifiers" for scanf, read quite a few things but none solves this.
The code is shown below -
#include <stdio.h>
#include <conio.h>
int main()
{
int a;
char b;
printf ("Enter an integer \n");
scanf_s(" %d", &a);
printf("Enter a character \n");
b = getchar();
printf("The integer you entered is %d \n", a);
printf("The character you entered is %c \n", b);
_getch();
return 0;
}
The output is as below -
Enter an integer
4563
Enter a character
The integer you entered is 4563
The character you entered is
The enter key I press at the end of integer entry is being returned by getchar. The screen does not even stop after printing "Enter a character". What is the correct way to do this ?
Use the scanf(" %c", &b) instead of getchar()
When you put the space befor the %c you clean the buffer
Or you can clean the buffer using this too:
int ch;
while ((ch = getchar()) != '\n' && ch != EOF);
Complete example:
int main(void)
{
printf("Enter an integer \n");
int a;
scanf(" %d", &a);
int ch;
while ((ch = getchar()) != '\n' && ch != EOF) {
}
printf("Enter a character \n");
char b = getchar();
printf("The integer you entered is %d \n", a);
printf("The character you entered is %c \n", b);
_getch();
}
But I think the scanf()

C while loop extra iteration

I'm attempting input verification of the scanf function. I've already fixed the input to ignore blank space (" %c....").
Can anyone see what I've done wrong?
#include <stdio.h>
#include <stdlib.h>
int main() {
char c1, c2, c3;
int k, done = 0;
float x;
double y;
do {
printf("\n%s\n%s\n%s\n%s", "Input the following: three characters,", " an int,", " a float,", " and a double: \n");
if(scanf(" %c%c%c%d%f%lf", &c1, &c2, &c3, &k, &x, &y) == 6){
printf("\nHere is the data that you typed in: \n");
printf("%3c%3c%3c%5d%17e%17e\n\n", c1, c2, c3, k, x, y);
done = 1;
} else {
printf("Invalid input!");
}
} while (done != 0);
return EXIT_SUCCESS;
}
First of all variable done was not initialized and has an indeterminate value
int k, done;
//...
while(done != 1){
You must initialize it for example like
int k, done = 0;
But it would be better to write a more suitable loop. That is instead of the while loop it is better to use do-while loop. For example
int done = 0;
//...
do
{
printf("\n%s\n%s\n%s\n%s", "Input the following: three characters,", " an int,", " a float,", " and a double: \n");
if(scanf(" %c%c%c%d%f%lf", &c1, &c2, &c3, &k, &x, &y) == 6){
printf("\nHere is the data that you typed in: \n");
printf("%3c%3c%3c%5d%17e%17e\n\n", c1, c2, c3, k, x, y);
done = 1;
} else {
printf("Invalid input!");
}
} while ( done != 1 );
Secondly in the scanf call you should specify balnks for format specifiers %c
For example
if(scanf(" %c %c %c%d%f%lf", &c1, &c2, &c3, &k, &x, &y) == 6){
You forgot to initialize your variables. At least done should be initialized to something that's not 1.
You forgot to read and discard the rest of an invalid input line. Add e. g.
scanf("%*[^\n]%*c");
in the else block.

How to stop a program based on user's input in C

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;
}

Resources