Validating integer values; c program - c

I need to program a code that asks the user to input valid positive integer values and then display error messages when it is not an integer for ex. if it is either a 0 , -1, or character/string. I tried making a do while loop so that it continues to scan again if the input is wrong, but it keeps an infinite loop. And this after this I need to take this value and plug it into a conversion function that I already have. How do I do that? Here is my code so far:
#include <stdio.h>
int scanf(const char *format, ...);
int user_interface();
double convert(double);
void print_table(int);
int user_interface()
{
int Kelvin;
char term;
int status;
int wrong = 0;
printf("\t\n");
printf("Hello, and welcome to homework1a program where\n");
printf("this program will request input from the user to\n");
printf("enter a value for Kelvin and then it will return\n");
printf("the acquired integer\n");
printf("\t\n");
do
{
printf("Enter a maximum value to show: ");
fflush(stdin);
status = scanf("%d%c", &Kelvin, &term);
if(status < 0)
{
printf("WRONG This is not correct %d\n", Kelvin);
wrong = 1;
}
else if((status) != 2 || term != '\n')
{
printf("Error: %d\n", Kelvin);
wrong = 1;
}
} while (wrong);
return 0;
}
int main(int argc, char *argv[])
{
void print_table(int num);
double convert(double Kelvin);
user_interface();
return 0;
}

1. Program getting stuck in a loop after wrong input.
So pretty much right now in your do-while loop you are using the "wrong" variable to determine if it should loop over again.
You have only been setting it to 1 when it is incorrect. It is getting stuck in a loop as the "wrong" variable is never being set back to 0.
In the do-while loop you need somewhere to include "wrong = 0;"
It is up to you where you choose to do this, you can either put it at the beginning of the do-while loop OR after the else if statement you can add an else statement.
else
{
wrong = 0;
}
Up to you how you want to implement it :) but just make sure the "wrong" variable gets reset or else once the user puts in the incorrect input 1 time the program will keep looping since the variable has not reset.
2. How to get the value into your conversion function.
So right now your "conversion" function can take in a double and the "user_interface" function returns an int so you can probably have the return statement plug in the value into the "conversion" function, but in saying that if you were expecting to receive a double in the "conversion" function I would recommend re-evaluating if the "user_interface" should be returning an int or a double.
Hoped this helped...

Related

How can I resolve Code will be never executed error

I am making a program that reads input from a user then check the validity,
but for the while statement in the validateInput function I am getting an warning
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>
int ValidateUser(char *);
int ValidateInput(int);
FILE *database;
struct{
int year;
int unit;
float gpa;
char semester;
char grade;
char name[40];
}student;
int ValidateInput(int x)
{
while (x != 1 || x != 2 || x != 3) // code that causing a warning
return x;
}
int ValidateUser(char *input)
{
int result;
result = strcmp(input, student.name);
if (result == 0)
{
return 1;
}
else
{
while (result != 0)
{
printf("The Username you entered does not exit. Please enter correct name.");
}
}
return 1;
}
int main()
{
printf("\t----------------------------------------------------------\n");
printf("\t|\t\t\t\t Santa Monica College\t\t\t\t\t |\n");
printf("\t----------------------------------------------------------\n\n");
printf("\t\tWelcome to Santa Monica Student Record System.\n\n");
printf("Please Enter Your Option\n");
printf("\t1.View GPA/GRADE\n");
printf("\t2.Add New GPA\n");
printf("\t3.Modify Information\n");
int choice;
scanf("%d", &choice);
char UserName[40];
if(choice == 1)
{
printf("Please enter your name\n");
scanf("%s", UserName);
ValidateUser(UserName);
printf("The GPA of %s is %f , %c ", student.name, student.gpa, student.grade);
}
else if (choice == 2)
{
printf("Please enter your name\n");
scanf("%s", UserName);
ValidateUser(UserName);
}
else if (choice == 3)
{
printf("Please enter your name\n");
scanf("%s", UserName);
ValidateUser(UserName);
}
else
{
ValidateInput(choice);
}
return 0;
}
The ide was suggesting to add parentheses around x-values in the argument of while statement in the ValidateUser to make it silence
I've done some research on this warning and I found that the condition I made is not true so that's why I am getting it, but I am not quite sure what the problem is.
Can someone help me out with this???
In validateUser(), your program will reach the
while (result != 0)
only in the event that the while condition is initially true, so if it reaches the loop, it will enter it. The body of the loop does not modify result, so if it enters the loop, it will loop indefinitely.
Ultimately, if the first branch of the if / else is taken, then the function returns from within that branch, and if the second branch is taken then control never exits that branch. Either way, the
return 1;
at the end of that function cannot be reached. Of course, that's just a symptom. The infinite loop is the main problem.
It's unclear what behavior you actually want here, but what would be most in keeping with the name of the function would be for it to only evaluate whether the specified user name is valid, returning a result that conveys either "yes" or "no". There is no particular reason why such a function would need to loop at all.
You put while (result != 0) inside function ValidateUser(char *input) and never put a way to get out of the loop, resulting in the return value below it never running.
To fix this, you would need to add a break; somewhere in the loop to indicate that you are ready to leave the current loop, or make result = 0;
The difference between the two is that break; will indicate that the rest of the loop doesn't need to run and will jump out of the loop, or use result=0; to run the rest of the code in the loop and then jump out of it

Can't get while loop to work 2 times? (C)

So I'm trying to loop the name asking section as well as the age one, the age one worked fine but when I tried to do it with name one it doesn't work. What I'm just trying to achieve is that when you put a number in the name section or vice versa, you get an error message and it loops you back to the same question
#include <stdio.h>
int vek;
char name[20];
int result1;
int result2;
int main()
{
FindName();
void FindName() { // it wants me to put a ";" which doesn't make sense to me and doesn't work
printf("Napis svoje meno \n");
result2 = scanf("%s",&name);
while (gethar() != '\n');
if(result2 == 1){
printf("Ahoj %s \n",name);
break;
system("pause");
}
else {
printf("nepis sem cisla ty kokot \n");
}
findAge();
}
void findAge() {
printf("Napis svoj vek \n");
result1 = scanf("%d",&vek);
while (getchar() != '\n');
if(result1 == 1){
printf("%s si krasny %d rocny priklad downoveho syndromu \n ",&name,vek);
}
else {
printf("co si jebnuty \n");
findAge();
}
}
I've tried to just break the loop if it's the right answer but that wouldn't work either, I'm just a beginner
The while loop will run everything inside the body as long as the condition is true. You need to put the code that needs to be repeated in a block, between { and }. You've put a semicolon behind it. That means a null statement, or do nothing. That way the condition is checked until it is no longer true, but nothing else is done. For example:
int i=0;
while(i < 3) {
printf("%d\n", i);
i++;
}
That will print the numbers 0,1 and 2. And then it stops because the condition is no longer true.
You want the program to look like this. In pseudocode:
main:
call findName
call findAge
findName:
print "Something Eastern European asking for a name"
result = 0;
while result != 1:
result = read input
if result == 0
print "Try again"
And the same for findAge
Notice the functions never call themselves. They just run the loop until the input is valid.

Compiler error in C, Error : Expected Expression

I have run into a problem I don't really know how to fix. I mostly code in Python, and this is my first program in C.
#include <stdio.h>
int ask(void) {
scanf("Var");
return 0;
}
int count(ask) {
scanf("number1");
return 0;
}
int main(void) {
printf("This is my first program!\n");
printf("I hope this program turns out well.");
printf("I don't really know what to do, but i think im progressing.\n");
printf("But yeah, This is my first program.\n");
printf("Type an Number");
ask();
count(ask());
printf("Thanks!");
printf(%count%);
return 0;
}
However, I keep getting an error.
main.c:22:10: error: expected expression
printf(%count%);
^
main.c:22:17: error: expected expression
printf(%count%);
^
2 errors generated.
compiler exit status 1
What I want it to do is, the user types a number, and then it prints out that number. It's not complete though. I want it to write numbers 1 - the users input, and when it gets the number right, it prints "Your number is:" (number)
The problem (as already pointed out) is that you aren't actually getting and storing the value from the scanf() call. Additionally, printf(%count%) is not valid C syntax. You need to use printf("%d", count).
Putting all that together:
#include <stdio.h>
int ask(void) {
int input_number;
scanf("%d", &input_number);
getchar(); # This is so that the '\n' in is read when you hit Enter
return input_number;
}
int main(void) {
printf("This is my first program!\n");
printf("I hope this program turns out well.");
printf("I don't really know what to do, but i think im progressing.\n");
printf("But yeah, This is my first program.\n");
printf("Type an Number");
int input_number = ask();
printf("Thanks!");
printf("The number you entered is %d\n", input_number);
return 0;
}
Some things to read to avoid making mistakes like these:
printf tutorial: https://www.tutorialspoint.com/c_standard_library/c_function_printf.htm
scanf tutorial: https://www.tutorialspoint.com/c_standard_library/c_function_scanf.htm
You are using incorrect format for printing.
you are using this code printf(%count%); instead you should use this code printf("%d",count(variablename));
Here is the code that you can use:
#include <stdio.h>
int ask(void) {
//scanf("Var");
int var; //declaring integer type varible in C
scanf("%d",&var); //taking input
return var; //returning what is being input by user
}
//int count(ask) //its function you are passing
//so it should have parenthesis
int count( int a )
{
return a;
}
int main(void) {
printf("This is my first program!\n");
printf("I hope this program turns out well.");
printf("I don't really know what to do, but i think im progressing.\n");
printf("But yeah, This is my first program.\n");
printf("Type an Number: ");
//ask();
count(ask()); // when you will call it will automatically run ask as well
// and it will pass int value that user will input
printf("Thanks!");
int var1=ask(); // this varible var1 will store value returned by ask()
printf("%d",count(var1) ); //this will print that value
//I dont know what you wanted to do here
//maybe you wanted to print value returned by count function
//so it can be done by this
return 0;
}
printf format: printf("%formatspecifier",variable name); Format specifiers are %d for a integer. %f for a floating value. %c for a charcater. s for a string and so on.
In C, we use % to specify output/input type. %d for integer, %f for float, %c for character, %s for string and thats your basic knowledge.
for printf:
printf("%d", varname);
for scanf:
scanf("%d", &varname);
'&' means location in memory.
Your program got many syntax errors, here is some code:
#include<stdio.h>
int ask(){
int varin;
scanf("%d", &varin);
return (varin);
}
int count(int countin){
return (countin); //just an example code, or whatever you wanna do here.
}
int main(){
int out;
printf("Whatever\n");
out = ask();
count(out);
printf("%d", out);
return 0;
}

Taking input from command input in C and making a calculation

First poster here, and forgive me for the basic ask, but I cannot seem to get my head around as to why this code won't work.
I'm trying to take to input from command line, and perform a simple calculation, however, when I debug the code, the error message that I created from the if statement shows, and not the result of the calculation.
Here's the code that I have made;
#include <stdio.h>
#include <stdlib.h>
int main (int argc, char *argv[]) {
int num1 = 0;
int num2 = 0;
int sum = 0;
int errors = 0;
int read = 0;
if (argc != 3){
errors++;
printf("Error: Less/more than 2 numbers entered.");
}
if (argc == 3){
read = sscanf(argv[1], "%d", &num1);
read = sscanf(argv[2], "%d", &num2);
if (read ==2){
sum = num1 + num2;
printf("%d", sum);
}
else{
printf("something weird happened...");
}
}
}
The values i have in command input is "4" and "3" (without the quotes and a space to separate them). So, the output should be the sum, which would be 7. But I just get the error message "Something weird happened...", which is obviously what I put into the if statement if the above failed.
My guess is it's something to do with my method of using the sscanf() twice? Forgive me, I'm a student learning this stuff for the first time. I have tried reading the book on C and have my lecturers code, but I think I learn better by trial and error, and seeing how it's supposed to work. Any help or guidance would be much appreciated.

How to check if user input is not an int value in C

I need to check if a user input value is not an int value. I've tried different combinations of what I know but I either get nothing or random errors
If the user inputs any char it'll raise a warning message
this is what ive written
#include <stdio.h>
//C program to perform addition, subtraction, multiplication, division + - * /
int main()
{
int num1,num2;
char alpha[30]
printf("enter numbers:\n\n");
printf("number 1: ");
scanf("%d",&num1);
printf("number 2: ");
scanf("%d",&num2);
// write a funcntion that when a char is entered to display an error
if (num1//and num2 == alpha)
printf("error");
else {
printf("Rezultat: \n");
printf("sborut im e: %d\n",num1+num2);
printf("ralikata im e: %d\n",num1-num2);
printf("proizvedenieto im e: %d\n",num1*num2);
printf("ralikata im e: %d\n",num1/num2);
}
return 0;
}
Scanf has a return value for a reason.
1-3) Number of receiving arguments successfully assigned (which may be zero in case a matching failure occurred before the first receiving argument was assigned), or EOF if input failure occurs before the first receiving argument was assigned.
4-6) Same as (1-3), except that EOF is also returned if there is a runtime constraint violation.
Here is an example program using that information:
#include <stdio.h>
int main(int argc, char **argv) {
int inputInteger;
printf("Please provide some input.\n");
if(scanf("%d", &inputInteger) == 1) {
printf("You inputted an integer\n");
} else {
printf("You did not enter an integer\n");
}
return 0;
}
Output:
./a.out
1[Enter]
You inputted an integer
./a.out
hello[Enter]
You did not enter an integer.
Note: I feel obliged to inform you that scanf() is not the best way to get input. See this answer for more details.
EDIT: I changed if(scanf("%d", &inputInteger)) to if(scanf("%d", &inputInteger) == 1) so that EOF will not output that an integer was found (pointed out by chux in the comments).
a try/catch approach works, with casting to int the test is caught by the compiler
std::string input;
std::getline(std::cin,input);
int input_value;
try {
input_value=boost::lexical_cast<int>(input));
} catch(boost::bad_lexical_cast &) {
// process bad input here
}

Resources