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.
Related
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.");
}
}
after making progress and rewriting most of the code for our calculator project, i run into a problem.
as the title suggest i need help with reinitializing the variable after loop or in every loop.
problem:
It should to like this:
as you can see instead of prompting an error it still calculate, suggesting that the inputed int was stored in my variable. which i maybe wrong or something but if i cannot fix these i make more progress.
Here is the code:
#include <stdio.h>
#include <stdbool.h>
//bool function
bool isInteger(double val)
{
int truncated = (int)val;
return (val == truncated);
}
int main(int argc, char *argv[])
{
//local variable
double a, b;
char operation, option = 'y';
//loop
while(option == 'y' || option == 'Y')
{
//system("cls");
printf("Enter number and operator to solve:\n\nExapmple [a + b][a - b][a * b][a / b]\n");
scanf("%lf %c %lf", &a, &operation, &b);
// nested if
if(isInteger(a) && isInteger(b))
{
if(operation == '+')
{
printf("Result: %.1lf\n\n", a + b); //ouput result
}
else if(operation == '-')
{
printf("Result: %.1lf\n\n", a - b); //ouput result
}
else if(operation == '*')
{
printf("Result: %.1lf\n\n", a * b); //ouput result
}
else if(operation == '/')
{
printf("Result: %.1lf\n\n", a / b); //ouput result
}
else
{
//output error
printf("Invalid Operater!\n");
}
}
else
{
//output error
printf("Input is not a digit!\n");
}
//output selection
printf("Do you want to retry [y]/[n]?");
option = getch(); //not recommended but just a small project
//scanf("%c", &option); -- stops the loop
} //end loop
}
In your second example (i.e., second time around), this line
scanf("%lf %c %lf", &a, &operation, &b);
tries to read an a into a double which will cause scanf to fail and return early.
Check the documentation of scanf and you'll see that it returns the number of values read and will set errno on failure. These must be checked before a, operation and b can be safely used.
Im making a calculator with A LOT of functions, Im not nearly done with the functions. But I thought, I want the program active after returning me the value I asked for. My logic was to put it into a while loop, but clearly my idea and how I put it are not equal. Or maybe my logic doesnt work in this case. Anyway, imagine I ask the program how much its 2+2 and it returns me 4. Done, but I want it to ask me again for another operation, how can I do that?
Im really new with this stuff, so thanks for the help.
To resume the code below. I ask for a value, then scan it, then ask for a operator, then I ask wether if the user want to continue or not, if he says yes thats the condition for the loop ---> while(condition != 'yes' );{
And if not, just end the program. And I putted the operations inside the loop.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
int input;
double sinus;
int op;
printf(" What function do you want to use? \n \n --------------------------------------- \n");
printf(" BASIC OPERATIONS --> type 1 \n --------------------------------------- \n");
printf(" TRIGONOMETRIC FUNCTIONS \n sin --> type 2 \n cos --> type 3 \n tan --> type 4 \n arcsin --> type 5 \n arccos --> type 6 \n arctan --> type 7 \n --------------------------------------- \n");
scanf("%d", &op);
char condition[5];
printf("Stop? Type: yes or no");
scanf("%s", &condition);
while(condition != 'yes' );{
if (op == 1) {
double val1;
char op1;
double val2;
printf("Please type a number: \n" );
scanf("%lf", &val1);
printf("Please type an operator: \n" );
scanf(" %c", &op1);
printf("Please type another number: \n" );
scanf("%lf", &val2);
if (op1 == '+') {
printf("%f \n", val1 + val2);
}
if (op1 == '-') {
printf("%f \n", val1 - val2);
}
if (op1 == '*') {
printf("%f \n", val1 * val2);
}
if (op1 == '/') {
printf("%f \n", val1 / val2);
}
}
else if (op == 2) {
double arg;
printf("Please type the argument of sin(x) \n");
scanf("%lf", &arg);
printf("The value is %f", sin(arg));
}
else if (op == 3) {
double arg;
printf("Please type the argument of cos(x) \n");
scanf("%lf", &arg);
printf("The value is %f", cos(arg));
}
else if (op == 4) {
double arg;
printf("Please type the argument of tan(x) \n");
scanf("%lf", &arg);
printf("The value is %f", tan(arg));
}
else if (op == 5) {
double arg;
printf("Please type the argument of arcsin(x) \n");
scanf("%lf", &arg);
printf("The value is %f", asin(arg));
}
else if (op == 6) {
double arg;
printf("Please type the argument of arccos(x) \n");
scanf("%lf", &arg);
printf("The value is %f", acos(arg));
}
else if (op == 7) {
double arg;
printf("Please type the argument of arctan(x) \n");
scanf("%lf", &arg);
printf("The value is %f", atan(arg));
}
else {
printf("%d", 0);
}
}
}
Sorry for too many to read:((( Im not experienced with forums.
The following example will give you an idea how things can be repeated based on input.
check how strcmp is done,that way you are doing is wrong.
Also consider using switch for handling multiple cases of input and their operations.
#include<stdio.h>
#include <string.h>
#include <ctype.h> // isspace
int main() {
char choice[] = "Yes";
do{
int i = 0;
/**
* implement all you want here
*/
printf("Enter Yes to repeat, to exit enter any other non blank string\n");
while(isspace(choice[i] = getchar()));
while((choice[++i] = getchar()) != '\n');
choice[i] = '\0';
printf("choice = %s, i = %d\n", choice, i);
}while(!strcmp(choice,"Yes") );
return 0;
}
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*/
}
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
int main()
{
int a, result;
float b;
printf("**This is a simple arithmetic calculator.** \n");
printf("\n Please enter an integer: ");
scanf("%i ", a);
printf("Please enter a floating point number: ");
scanf("%f", b);
result = a + b
printf("Output: ");
printf("%i + %f = %lf \n", a, b, result);
printf("%i - %f = %lf \n", a, b, result);
printf("%i * %f = %lf \n", a, b, result);
}
I need to ensure that your program will not crash if the user enters an invalid input.
scanf is a function that has also got a return value which indicates how many inputs were inserted correctly.
So you can just do something like:
while (scanf("%i ", a) != 1)
{
printf("wrong input, try again");
}
use while loop or if for scanf
while(scanf("%i ", a) !=1){
printf("invalid input.\n");
}
and
while(scanf("%f", b) !=1){
printf("invalid input.\n");
}