Taking input from command input in C and making a calculation - c

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.

Related

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.

Validating integer values; c program

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...

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

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
}

Prompt for input and print a response with only one printf()?

C-code only: Ask user if they are married or not. User must input 0 for false. User must input any other character for true. Do it using only one printf.
Ok, so I always turn to stackoverflow as a last resort, because I am trying to figure it out. This, is what I came up with but I get errors and I have done other things like take out scanf("%f", &t), because that is essentially unnecessary. I also made char married[3]; char married[] ="; instead but that doesn't work.
Here is my code:
#include <stdio.h>
#include <string.h>
int main()
{
char married[3];
unsigned long t;
int f;
scanf("%f", &t);
scanf("%d", &f);
printf(" For the following question: Enter 0 if false. Enter anything but 0 if true. Are you married? %s", married);
if (f == 0)
{
married == "no";
}
else
married == "yes";
return 0;
}
Thanks the help is appreciated. Please go easy on me just learning...
I'm not sure you are interpreting the question correctly. It says to print whether the person is married or not. So that's the expected output. It suggests you can do that with one printf. It does not mean the whole program only has one printf so you are allowed to have another printf for the user prompt. It just means avoid using two printfs for the output (one for YES and another for NO). One way to do this is to use the ? operator.
For example:
#include <stdio.h>
#include <string.h>
int main(void)
{
int married = 1;
printf(" For the following question: Enter 0 if false. Enter anything but 0 if true. Are you married?");
scanf("%d", &married);
printf("You %s married\n", married ? "ARE" : "ARE NOT");
return 0;
}
#include <stdio.h>
#include <string.h>
int main() {
char married[4]; //Space for 'yes' + the NUL-terminator
//unsigned long t; Why do you have this?
int f = 1; //Initialize variables
//scanf("%f", &t); ??
//scanf("%d", &f); Wrong place
printf(" For the following question: Enter 0 if false. Enter anything but 0 if true. Are you married?"); //Remove %s and the argument. You are trying to print an uninitialized array
scanf("%d", &f); //scan input after printing
if (f == 0)
strcpy(married, "no");
else
strcpy(married, "yes"); //Copy strings using strcpy function
return 0;
}

Resources