#include<stdio.h>
#include <cs50.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
int main(int argc, string argv[])
{
if (argc == 2)
{
printf ("%s \n", argv[1]);
if (isdigit (argv[1]) !=0)
{
printf("Success\n");
printf("%s \n", argv[1]);
}
else
{
printf(" %s key \n", argv[0]);
}
}
else
{
printf(" %s key \n", argv[0]);
}
}
Hello everyone, I am trying to run this program that takes command line arguments and checks them for digits.After that I have to store it into a variable. I am stuck and it is giving the error "Segmentation fault". I googled it and I think it means that the program is not able to read the value. Please let me know why it is giving the error, what "Segmentation fault" means and how to fix it.
I believe the problem is in
isdigit (argv[1])
argv[1] is of type char *, but isdigit() expects an int.
If you want to check whether the supplied argument is all-numerical value or not, you have to either
Loop over the elements in argv[n] and pass them one by one to isdigit() check.
use strtol() or similar to check for the validity.
The error in on line 13,
You need to do a
...
13: if (isdigit (atoi(argv[1])) != 0)
...
Related
I am getting an error "Segmentation fault". I think it has to do with the isdigit(argv[i]) line but do not uderstand why.
#include <stdio.h>
#include <cs50.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
//implement commandline arguments
int main(int argc, string argv[])
{
//convert string element in array to integer
int key = atoi(argv[1]);
//check that user input for key is no more than 2 memory spots, not a negative number and a single input
if (argc != 2 || key < 0 || isdigit(argv[1]))
{
printf("useage: ./caesar key\n");
return 1;
}
else
{
string plaintext = get_string("plaintext: ");
printf("ciphertext: %s \n", plaintext);
return 0;
}
}
Assuming you do actually have a valid string passed as an argument, then argv[1] refers to that entire string. To check if the second character of that string is a digit, you need to further 'dereference' that string, and use: isdigit(argv[1][1]). Or, for the first character of that string, use argc[1][0] (or *argv[1]).
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;
}
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;
}
I just need an extra set of eyes to help me find out why this code is segfaulting.
//------------------------Preprocessor Instructions. ------------------------------------
#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
#define NUMBER 128 //Maxmimum number of items/lines in file.
#define BUFFER 120 //Buffer length (For user input)
#define LENGTH 32 //Maximum length of lines in file.
//------------------------Global stuff. ---------------------------------------------
int iterations=0; //Will count number of times the calculation function is called.
int weight[NUMBER];
int value[NUMBER];
char object[NUMBER][LENGTH];
//------------------------Function Definitions. -----------------------------------------
void printarr();
//------------------------Printarr -- Array printing function. --------------------------
void printarr()
{
int i,j;
printf("\n");
printf("Weight \t Value \t Object \n");
for(i=0;i<4;i++){
printf("%d \t %d \t %s \n", weight[i], value[i], &object[i][0]);
}
}
//------------------------Main. ---------------------------------------------------------
int main(int argc, char **argv)
{
FILE *fp; //File pointer.
char buffer[BUFFER]; //Temporary storage
int result; //sscanf return value.
int capacity; //User input.
int i,j=0; //Loop counters.
//Command Line Argument Parsing: Assigns input value to capacity.
if (argc != 2){
printf("Usage: %s number. Max 1024. \n",argv[0]); //Usage: *program* *num*
return(1);
}
if (1 != sscanf(argv[1],"%d",&capacity)){
printf("Usage: %s number. Max 1024. \n",argv[0]);
return(1);
}
//File reading.
fp=fopen("knapsack.data","r");
if(NULL==fp){
printf("Error opening file. \n");
exit(0);
}
//Write to arrays.
while(NULL != fgets(buffer, BUFFER, fp)){
result=sscanf(buffer, "%d %d %s", &weight[i], &value[i], &object[i][0]);
i++;
}
//Print the arrays.
printarr();
fclose(fp);
}
According to GDB it segfaults when it hits the sscanf statement. But as far as I can tell there's nothing wrong with the way I'm accessing the locations... clearly I'm mistaken. Any help would be appreciated.
Edit: I was half right, fix this line:
result=sscanf(buffer, "%d %d %s", &weight[i], &value[i], &object[i][0]);
to look like this:
result=sscanf(buffer, "%d %d %s", &weight[i], &value[i], object[i]);
You are reading in a whole string, so you need to write to the c string location, in this case, object[i]. Also, init i for best practice (although gcc does init ints to zero if uninitialized, try it yourself and see).
Edit: Ignore the downvote, I am correct but I did make an error in forgetting to remove your second index, you can access a c string 2d array with object[i] or &object[i][0], both work. object[i] for accessing an entire string looks cleaner to me than using &object[i][0].
When I run the program and answer "yes", it tells me that I am wrong. Does anybody know a way to execute this type of program?
#include <string.h>
#include <stdio.h>
int strcmp(const char *str1,const char *str2 );
// I am trying to make a program that asks the user to input an answer
int main()
{
char answer[20];
printf("Can birds fly?\n");
scanf("%s", &answer[20]);
if(strcmp(answer, "yes") == 0)
{
printf("You are right");
}else
{
printf("You are worng");
}
return 0;
}
Change this line:
scanf("%s", &answer[20]);
to:
scanf("%s", answer);
You have to pass to scanf the address where you want to put the string, with answer[20] you pick the value of the 21th character in the string (undefined because the string is 20 characters only) and then take a pointer to it (garbage, you may even get an access violation).