validate the number of inputs in c - c

I'm writing a code which needs to accept command line input. input validation is part of the marking criteria so I'm writing a piece of code to check that exactly one number is entered so I can put it in the main code later (adding an else case for invalid input to bug the user)
#include<stdio.h>
int main(int argc, char* argv[])
{
double a;
a = 75;
if(argc == 2);
{
sscanf(argv[1], "%lf", &a);
printf("%lf \n", a);
}
printf("%d% \n", argc);
return(0);
}
the program prints a when at least one argument is on the command line but it prints a segmentation fault when no argument is entered and still scans when more than one are.
help?

if(argc == 2);
is equivalent to
if(argc == 2)
;
You need to remove the ; to have the block after this be executed conditionally
if(argc == 2)
// ^ no trailing ; now
{
sscanf(argv[1], "%lf", &a); // now only executed if argc == 2

Related

using if statements with command line parameters in c

I am having trouble with getting my if statements to work with parameters from the command line. I get an error saying, 'comparison between pointer and integer ('char *' and 'int')' every time. Any help will be greatly appreciated. Here is the description for what I have to do:
This program will read a parameter from the command line and translate it to the name of the corresponding month. I.e. if you run the program with the following parameter:
It will print the following message:
The month is 'April'.
#include <stdio.h>
int main(int argc, char *argv[]) {
if(argv[1] == 1){
printf("You entered the number 1.");
} else {
printf("You entered a different number.");
}
return 0;
}
The parameters passed on the command line are strings, so you need to use strcmp to compare them.
int main(int argc, char *argv[]) {
if(argc > 1 && (strcmp(argv[1],"1") == 0)){
printf("You entered the number 1.");
} else {
printf("You entered a different number.");
}
return 0;
}
Compiler is right - you are comparing char * and int.
You have to either convert argv[1] to int (e.g. with strol()) or convert 1 to char * (by adding quotes - "1") and then compare with strcmp() instead of ==.
And checking number of arguments in argc is also something you should do, when working with arguments. (thanks #Ingo Leonhardt)
Argv returns pointer to array of chars, so your programm must looks like:
#include <stdio.h>
int main(int argc, char *argv[]) {
if(argv[1][0] == '1'){
printf("You entered the number 1.");
} else {
printf("You entered a different number.");
}
return 0;
}
Or you can use atoi (man 2 atoi) function to convert ascii array to int like this:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
if(atoi(argv[1]) == 1){
printf("You entered the number 1.");
} else {
printf("You entered a different number.");
}
return 0;
}
If you want to use your command line parameter like a integer, you must modify the type with atoi
#include <stdio.h>
int main(int argc, char *argv[]) {
if(atoi(argv[1]) == 1){
printf("You entered the number 1.");
} else {
printf("You entered a different number.");
}
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.

C getting input from CMD

How do you get input using prompt? I tried compiling the code bellow into "a.exe" and executing it from CMD like "gcc a.exe 5", but it doesn't output the number like it was supposed to.
#include <stdio.h>
int main(int a)
{
printf("%d\n", a);
return 1;
}
Have I done anything wrong when installing the compiler or am I trying to run it wrong?
Your main() parameters are wrong, you should do it this way:
int main(int argc, char **argv) {
if(argc > 2) {
printf("%s\n", argv[2]);
}
else {
printf("No arguments\n");
}
}
Note that int argc represents the number of parameters and char **argv is an array containing all the parameters, as strings, including "gcc", "a.exe", etc.
In your case, if you run your program this way: gcc a.exe 5, your parameters would be: argc = 3, argv = ["gcc", "a.exe", "5"]
To get input using the prompt, the easiest way would simply be to use a scanf statement. scanf basically waits for, and scans user input, which can then be stored as a variable. For example, a code that would take input for "Give me a number." and then spits back the result would be:
#include <stdio.h>
int main()
{
int num; //Initializes variable
printf("Please give me a number.\n"); //Asks for input
scanf("%d", &num); //scanf is the function, %d reserves the space, and the &*variable* sets the input equal to the variable.
getchar(); //Waits for user to input.
printf("Your number was %d.\n", num); //Spits it back out.
return 0;
}
The output would be:
[PROGRAM BEGINS]
Please give me a number.
>>>5
Your number was 5.
[PROGRAM ENDS]
#include <stdio.h>
int main(int argc, char *argv[])
{
if(argc == 2)
printf("%d\n", atoi(argv[1]));
return 0;
}

The Loop continues forever

The following code compiles and works as expected, despite one frustrating error in program flow that I don't understand ..
The loop in the middle of the main function works fine if I pass 2 or 5 as input. However, when I pass -3 or anything below zero (such as a character, which return -1), the loop continues forever and the program doesn't even pause for me to provide input for the scanf function ..
#include <stdio.h>
#include <stdlib.h>
void getNum(char * prompt, int*num)
{
printf("%s", prompt);
scanf("%d", num);
}
int main(int argc, char ** argv)
{
int num = -1;
while(num < 0) { // problem here
getNum("Number of times you go to the gym in a week: ", &num);
}
return EXIT_SUCCESS;
}
I wonder were the mistake is ..
I noticed something strange .. When I change the loop to a do-while loop it works just fine ..
int main(int argc, char ** argv)
{
int num;
do {
getNum("Number of times you go to the gym in a week: ", &num);
} while (num < 0); // this works fine ..
return EXIT_SUCCESS;
}
Also, for some reason, I recompiled the code and it worked fine ..
Can anybody explain this ?
After accept answer
scanf("%d", num);, upon reading non-numeric input simple returns 0, leaving *num alone. The offending text is still in stdin and subsequent calls will get the same text and same results. Code should check the scanf() result value.
// weak
scanf("%d", num); // fails to consume offending input.
// good
*num = 0; // default answer
int retval;
do {
printf("%s", prompt);
retval = scanf("%d", num); // returns EOF, 0, or 1
// consume rest of line
int c;
while ((c = fgetc(stdin)) != '\n' && c != EOF);
} while (retval == 0); // repeat is no number read and stdin still open
[Edit]
Avoid using scanf(). Offer How to test input is sane as a solution to well handle reading int.
You could try clearing STDIN data after you tried scanf :
void getNum(char * prompt, int*num)
{
printf("%s", prompt);
scanf("%d", num);
// clean stdin
char c;
scanf("%c",&c);
while (c != '\n' && c != EOF) scanf("%c",&c);
}

C programming minor issue with interactive menu when input a floating value

My program works well with invalid inputs such as char, number out of range, but a problem happens when a floating point value such as 1.2 is entered. The program prints menu again, and asks user for input before printing error message. What I try to fix is don't print menu again, but still struggle. For example,
Make your selection: 1.1
[Here is menu content]
Make your selection: That selection isn't valid. Please try again.
#include <stdio.h>
#define QUIT 0
int menu();
int main(void)
{
int choice;
char c;
choice = menu();
while(choice != QUIT) //execute so long as choice is not equal to QUIT
{
choice = menu();
}
}
int menu(void)
{
int option;
printf("Text Encoder Service\n\n");
printf("1.\tEnter name of input file (currently 'Secret.txt')\n");
printf("2.\tEnter name of output file (currently not set)\n");
printf("3.\tEnter number of characters data should be shifted (currently +7)\n");
printf("4.\tEncode the text\n\n");
printf("0.\tQuit\n\n");
printf("Make your selection: ");
while( (scanf(" %d", &option) != 1) /* non-numeric input */
|| (option < 0) /* number too small */
|| (option > 4)) /* number too large */
{
fflush(stdin); /* clear bad data from buffer */
printf("That selection isn't valid. Please try again.\n\n");
printf("Your choice? ");
}
return option;
}
I finally could validate floating input. Thanks your advices so much! This is my new code. What else do you think an invalid input?
int menu(void)
{
int option, parsed_inputs;
char overcount_char;
parsed_inputs = 1;
printf("Text Encoder Service\n\n");
printf("1.\tEnter name of input file (currently 'Secret.txt')\n");
printf("2.\tEnter name of output file (currently not set)\n");
printf("3.\tEnter number of characters data should be shifted (currently +7)\n");
printf("4.\tEncode the text\n\n");
printf("0.\tQuit\n\n");
printf("Make your selection: ");
parsed_inputs = scanf_s("%d%c", &option, &overcount_char);
while( parsed_inputs > 1 ) /* number too large */
{
if((overcount_char != '\n') || (option < 0) || (option > 4))
{
fflush(stdin); /* clear bad data from buffer */
printf("That selection isn't valid. Please try again.\n\n");
printf("Your choice? ");
scanf_s("%d%c", &option, &overcount_char);
}
else
break;
}
return option;
}
An input of 1.1 leads to the following:
The string is read into an internal buffer.
It is then matched against the given format string.
On the first non-match, the scanf() call is stopped and it returns the number of successfully scanned values.
Let's test it:
#include <stdio.h>
int main(int argc, char ** argv)
{
while (1) {
int option;
int n = scanf(" %d", &option);
printf("%d %d\n", n, option);
if (n <= 0) break;
}
}
This program reads one line.
Suppose I enter 123 132.
Then the following happens:
* As the format string starts with a space, all leading whitespace is consumed. In this case, there is none.
* Then the 123 is consumed and put into option.
* As the format string is over now, parsing is stopped, n=1 and option=123.
* In the next loop run, the same happens, giving n=1 and option=123.
But: Suppose I enter 123.321 or 123#321.
Then the following happens:
* As the format string starts with a space, all leading whitespace is consumed. In this case, there is none.
* Then the 123 is consumed and put into option.
* As the format string is over now, parsing is stopped, n=1 and option=123.
* In the next loop run, there is no whitespace to skip. .321 resp. #321 is tried to be matched to %d, but these are no valid ints. Thus, we get n=0 and option keeps its old value.
* As no characters are consumed from the input stream (the one used is put back again), the same happens over and over again - that's why I put if (n <= 0) break;.
So you see that the behaviour has nothing to do with floating point, as it doesn't matter if we use . or # to "disturb".
We change our program to
#include <stdio.h>
int main(int argc, char ** argv)
{
while (1) {
int option; char c;
int n = scanf("%d%c", &option, &c);
printf("%d %d %d %c\n", n, option, c, c);
if (n <= 0) break;
}
}
and run it, inputting 4.235#6x7.
Then we get
* n=2, option=4 and c='.' at the first run
* n=2, option=235 and c='#' at the 2nd run
* n=2, option=6 and c='x' at the 3rd run
* n=2, option=7 and c='\n' (newline) at the 3rd run
and are prompted for further input.
This makes you open to the option
(parsed_inputs = scanf("%d%c", &option, &overcount_char)) < 1
and then check what overcount_char contains, whenever parsed_inputs is > 1.
I think you should put scanf() before the while loop and explicitly check "option" variable in the while loop.
What happening is that, here scanf() will always return the value 1, because scanf() returns no. of arguments read successfully. Hence this while loop will run forever. For further information check this link->http://www.cplusplus.com/reference/cstdio/scanf/
Hope this helps!

Resources