Segmentation fault: boolean expression - c

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

Related

While calculating length of the string array, any string characters entered after space are ignored

a beginner here. I was trying to get the length of entered string without using strlen() function. I wrote a program that counts each character present in the entered string until it reaches the null terminator (\0).
After running the program, I was able to calculate the length of the first word, but not the entire sentence.
Example : When I entered "Hello how are you?" , it calculated the length of the string only until "hello", the other characters after space were ignored. I want it to calculate the length of entire sentence.
Here's my code below.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdbool.h>
int main()
{
char str1[100];
int i = 0;
int count = 0;
printf("Enter the string you want to calculate (size less than %d)\n", 100);
scanf("%s", str1);
while (str1[i] != '\0') //count until it reaches null terminator
{
++i;
++count;
}
printf("The length of the entered string is %d\n", count);
return 0;
}
The %s format specifier reads characters up until the first whitespace character. So you'll only read in one word a a time.
Instead, use fgets, which reads a whole line of text at a time (including the newline).
Modify the code like this, which will solve the problem.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdbool.h>
int main()
{
char str1[100];
int i = 0;
int count = 0;
printf("Enter the string you want to calculate (size less than %d)\n", 100);
scanf("%[^\n]s", str1);
while (str1[i] != '\0') //count until it reaches null terminator
{
++i;
++count;
}
printf("The length of the entered string is %d\n", count);
return 0;
}

Why is the value of my strcmp not equal to 0 or invalid?

I am still new to programming and there are a lot of things I still don't know but I'd like to ask why my if statement doesn't seem to be working properly. It seems the value
of strcmp(bookName, tolower(searchedName)) when the variable searchedName = "introduction to c" is not 0.
Why is this?
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main() {
char bookName[30] = "introduction to c programming";
char searchedName[30];
printf("Enter the book you are searching for: ");
scanf("%s", &searchedName);
if (strcmp(bookName, tolower(searchedName)) != 0) {
printf("The book is not in elibrary");
} else {
printf("The book is in elibrary");
}
return 0;
}
tolower() is for converting characters, not strings. You will have to apply it to each characters in the string separately.
You don't need & before arrays in this case because arrays in expressions are automatically converted to pointers (except for some case).
%s in scanf() will stop at whitespace character. %[^\n] is useful to read until hitting a newline character.
Try this:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main() {
char bookName[30] = "introduction to c programming";
char searchedName[30];
char searchedName_lower[30];
int i;
printf("Enter the book you are searching for: ");
scanf("%[^\n]", searchedName);
i = 0;
do {
searchedName_lower[i] = tolower((unsigned char)searchedName[i]);
} while (searchedName[i++] != '\0');
if (strcmp(bookName, searchedName_lower) != 0) {
printf("The book is not in elibrary");
} else {
printf("The book is in elibrary");
}
return 0;
}

Check if input is a number [duplicate]

This question already has answers here:
Check if input is integer type in C
(16 answers)
Closed 5 years ago.
I have a bit of code that is supposed to get numbers from input until EOF and put them inside an array.
#include <stdio.h>
int main(){
int numbers[250000],i,m=0;
while(scanf("%d",&i)!=EOF){
numbers[m]=i;
m++;
}
}
My problem is that I need to check if the input is valid (if it is a number). If it is not a number I need to print out a message that says something along the lines "Wrong input" and end the program.
Can somebody please help me?
PS. I know that this question has been asked several time, I have googled, but I have not been able to figure out from the answers how to adapt the code to my situation. So, sorry if the question seems redundant.
scanf's return value is an integer, telling you how many items were succesfully read. If your single integer was read successfully, scanf will return 1.
#include <stdio.h>
int main(){
int numbers[250000],i,m=0;
int itemsRead = 0;
while(itemsRead = scanf("%d",&i) != EOF){
if (itemsRead != 1)
{
printf("Wrong input");
return 0;
}
numbers[m]=i;
m++;
}
}
Shortening #gssamaras code, you can have something simpler, like this
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <stdio.h>
int main()
{
int numbers[250000],i,m=0;
char temp;
while(scanf("%c",&temp)!=EOF)
{
if(!isdigit(temp)))
{
printf("Wrong input");
break;
}
numbers[m]=atoi(temp);
m++;
}
}
You need to read the input as a string, validate that its context is actually a number, and then assign it to the array's cell, like this:
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <stdio.h>
#define MAXINPUT 100
int main() {
int numbers[250000],m=0;
char input[MAXINPUT] = "";
while(scanf ("%s", input)!=EOF) {
for (size_t i = 0; i < strlen(input); i++)
if (!isdigit(input[i]))
{
printf ("Entered input is not a number\n");
exit(1);
}
// here we know that 'input' is a number
numbers[m] = atoi (input);
m++;
}
return 0;
}
PS: I would use fgets() instead of scanf().

Checking the return value of `isalpha`

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <math.h>
#include <string.h>
int main() {
char userPassword[20];
printf("Type in your password: \n");
scanf("%c", &userPassword);
if (isalpha(userPassword) == 0) {
printf("Nice");
} else {
printf("Nope");
}
return 0;
}
I'm trying to come up with a code where to check if the password contains only letters. Why does this code only work with the " == 0" sign. My friend told me to put this and my code works. What does the " == 0" do?
The signature of isalpha is int isalpha ( int c ).
Parameters
c character to classify
Return value
Non-zero value if the character is an alphabetic character, zero otherwise.
So, if c is not alpha, it returns non-zero, otherwise 0.
About the program:
scanf needs char *, not &userPassword, which is char **. scanf("%s", userPassword) is OK.
pass char to isalpha instead of char *.
If you want to check if a string is all alpha, you can simply iterate the string and check each single character. Like:
bool is_all_alpha(char *s) {
for (; *s!='\0'; ++s) {
if (!isalpha(*s)) return false;
}
return true;
}
http://en.cppreference.com/w/cpp/string/byte/isalpha

What is the issue with the following code? [duplicate]

This question already has answers here:
Issue with main arguments handling
(3 answers)
Closed 6 years ago.
I am learning C on my own but this code which seems right to me doesn't works right
#include <conio.h>
#include <stdio.h>
#include <stdlib.h>
main()
{
char name[20];
int p,c,m;
printf("Enter your name \n");
scanf(" %s", name);
if ( (name=='luv') || (name='pranav') )
{
printf("Enter your marks in pcm \n");
}
else
{
printf("get lost");
}
getch();
}
I want the correct code to run only if I enter name as luv or pranav but instead what is happening is that no matter whatever name i type it is running the code under else and i am not able to figure out the reason.
I am using codeblocks as compiler.
You cannot compare strings using ==, to compare strings, one has to use strcmp()
strcmp() returns 0 when the strings are same, other wise it returns the difference of those two strings,
So essentially, your code would become,
#include <conio.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h> // for the strcmp() function
main()
{
char name[20];
int p,c,m;
printf("Enter your name \n");
scanf(" %s", name);
// strings are given inbetween double quotes
// characters are given inbetween single quotes
if ( !(strcmp(name, "luv")) || !(strcmp(name, "pranav")) )
{
printf("Enter your marks in pcm \n");
}
else
{
printf("get lost");
}
getch();
}
NOTE:
1) Use the standard definition of main()
int main(void) //if no command line arguments.
2) Check the return of functions like scanf().
Lots of mistakes in the code.
I am trying to fix and show:
#include <conio.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h> // to use strcmp
int main(void) // int and void added
{
char name[20];
int p,c,m;
printf("Enter your name \n");
scanf("%19s", name); // no space before % and 19 to limit input
if ( !strcmp(name,"luv") // " instead of ' , and strcmp with operator !
|| strcmp(name,"pranav") == 0 ) // instead of ! you can use == 0
{
printf("Enter your marks in pcm \n");
}
else
{
printf("get lost");
}
getch();
}
main() is not a standard signature. You should use standard int main(void) unless you have some special reason to use non-standard signature.
'luv' and 'pranav' are multiple-character character constant, which have implementation-defined values. You should use string literals and strcmp() function.
name='pranav' is an assignment, and you cannot assign to what is converted from arrays, so this will emit compile error.
You should limit the length to read in order to avoid buffer overflow.
Try this:
#include <conio.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
char name[20];
int p,c,m;
printf("Enter your name \n");
scanf(" %19s", name);
if ( (strcmp(name, "luv") == 0) || (strcmp(name, "pranav") == 0) )
{
printf("Enter your marks in pcm \n");
}
else
{
printf("get lost");
}
getch();
}
remove #include <conio.h> and getch(); if they are not supported.
Two problems:
Single quotes are used for character constants, not string constants. You need to use double quotes for those.
Strings can't be compared with ==. What you're actually doing is comparing the address of the first element of name with a character constant. Even if you fixed the quotes on the constant, you'd be comparing the address of name with the address of a string constant, which are not the same. To compare strings, you use strcmp, which compares each character in the string.
So what you want is this:
if ( (strcmp(name,"luv") == 0) || (strcmp(name,"pranav") == 0) )
You'll also need to #include <string.h> to use strcmp.

Resources