#include<stdio.h>
#include<string.h>
int main()
{
char strg1[];
char strg2[] = "football"
printf("Enter first string: ");
gets(strg1);
if(strcmp(strg1, strg2)==0)
{
printf("\nEqual");
}
else
{
printf("\nNot Equal");
}
return 0;
}
I'm getting a string from the user as input and I want to compare it with a ready-made string I have, whether it's equal or not. When I try with strcmp, they are not equal. When I try with strncmp, for example, user footballABC wrote my string football is still equal because with strncmp it is 8 characters. I've limited it. Is there a solution?
You've done following mistakes in your program:
Not allocated space for char strg1[];(It will throw error while compiling).
error: definition of variable with array type needs an explicit size or an initializer
char strg1[];
Used gets() for reading string which can lead to Buffer Overflow.
while using gets() you should have been warned by compiler.
warning: this program uses gets(), which is unsafe.
Full article why gets() in not safe.
Corrected program:
#include<stdio.h>
#include<string.h>
int main()
{
// char strg1[]; // Error!
char strg1[100]; // Allocate space to Array.
char strg2[] = "football";
printf("Enter first string: ");
scanf("%s",strg1); // Use Scanf() instead of gets().
if(strcmp(strg1, strg2)==0)
{
printf("\nEqual");
}
else
{
printf("\nNot Equal");
}
return 0;
}
Related
Problem Statement
Today is Newton School's first class of this year. Nutan, a student at
Newton School, has received his first assignment. He will be given a
string as input. His task is to print "Gravity'' if the input is
"Apple''; otherwise, he will have to print "Space''.
Can you help Nutan in solving his first assignment? Note that the
quotation marks are just for clarity. They are not part of the input
string, and should not be a part of your output string. Input The
input consists of a single line that contains a string S (1 ≤ length
of S ≤ 10). The string only consists of lowercase and uppercase
letters. Output Print "Gravity'' or "Space'' according to the input.
What I am trying to do:
Basically, I am taking a user-defined string and trying to compare it with the hard input string i.e "Apple". If both the string matches then it will print "Gravity" or else it will print "Space"
#include <stdio.h> // header file for Standard Input Output
#include <stdlib.h> // header file for Standard Library
#include <string.h> // for strcmp() function
int main() {
char str1[10]="Apple";
char str2[20];
int value;
printf("Enter the input ");
scanf("%s", &str2[20]);
value = strcmp(str1, str2);
if(value==0)
printf("Gravity");
else
printf("Space");
return 0;
}
scanf("%s", &str2[20]);
may invoke undefined behavior by out-of-range access. You should:
Pass the pointer to the first element of the array, not one to the next element of the last element. (most) arrays in expressions are automatically converted to pointes to their first elements.
Specify the maximum length to read to avoid buffer overrun.
Check if reading succeeded.
The line should be:
if (scanf("%19s", str2) != 1) {
puts("read error");
return 1;
}
Some improvements:
Don't use "%s", use "%<WIDTH>s", to avoid buffer-overflow
Instead of using bare return 0;, use return EXIT_SUCCESS;, which is defined in the header file stdlib.h.
always check whether scanf() input was successful or not
Use const char * instead of char str1[10]
There's no need for int value;
SYNTAX ERROR: &str2[20]
There's no need for passing the address of str2 READ MORE
Initialize str2 with zeroes
Add 1 more space in your str2 for NULL ('\0') terminating character
Final Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
const char *str1 = "Apple";
char str2[21] = {};
printf("Enter the input ");
if(scanf("%20s", str2) != 1)
{
fprintf(stderr, "bad input\n");
return EXIT_FAILURE;
}
if(strcmp(str1, str2) == 0)
printf("Gravity");
else
printf("Space");
return EXIT_SUCCESS;
}
You are entering a string starting from the memory address after the last element of the array str2
scanf("%s", &str2[20]);
and then trying to compare the character array str1 with the non-initialized array str2
value = strcmp(str1, str2);
Change the call of scanf like
scanf("%19s", str2);
And the program will be safer if at least the array str2 will be initially initialized
char str2[20] = "";
Also as the array str1 is not changed then instead of the array you could declare a pointer to the string literal like
const char *str1 = "Apple";
And instead of the calls of printf
printf("Gravity");
//..
printf("Space");
it is better to use calls of puts
puts("Gravity");
//..
puts("Space");
Pay attention to that neither declaration from the header <stdlib.h> is used in your program. So you may remove this include directive
#include <stdlib.h> // header file for Standard Library
I have written this caesar cipher program in c language,it runs fine until I provide the integer value for key but after that it crashes.
can anyone please correct this code?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char alphabets[] = "abcdefghijklmnopqrstuvwxyz";
int arrow,key;
int search(char x)
{
for(arrow=0;arrow<strlen(alphabets);arrow++)
{
if(x==alphabets[arrow])
{
return arrow;
}
}
}
char cipherGenerator(int arrow)
{
arrow=arrow+key;
if(arrow>strlen(alphabets))
{
arrow = (arrow%strlen(alphabets))-1;
}
return alphabets[arrow];
}
int main()
{
char plain_text[]="",cipher_text[]="";
int i;
printf("Enter the plain text\n");
gets(plain_text);
printf("Enter the key\n");
scanf("%d",&key);
for(i=0;i<strlen(plain_text);i++)
{
strcat(cipher_text,cipherGenerator(search(plain_text[i])));
}
printf("The cipher text is %s:-",cipher_text);
return 0;
}
The crash can be explained by the attempt of writing into arrays of length 1.
char plain_text[]="",cipher_text[]=""; //these arrays have length 1
gets(plain_text); //will fail and crash here
strcat(cipher_text,cipherGenerator(search(plain_text[i]))); //will crash here
Regarding the usage of gets:
The gets() function does not perform bounds checking, therefore this function is extremely vulnerable to buffer-overflow attacks. It cannot be used safely (unless the program runs in an environment which restricts what can appear on stdin). For this reason, the function has been deprecated in the third corrigendum to the C99 standard and removed altogether in the C11 standard. fgets() and gets_s() are the recommended replacements.
Never use gets().
I wrote a C program which takes a string input from user and prints it on the screen.
int main (void)
{
char* string;
scanf("%s", string);
printf("%s", string);
return 0;
}
But the output was undesirable.
I gave input foo. Program printed out (null). Can anyone explain Why?
char* string;
This is just a pointer to a char. It doesn't point to any memory yet. You need to allocate memory for the characters that you want it to hold.
You can allocate memory using malloc()
#include<stdio.h>
#include<stdlib.h>
int main(void){
char *string;
string = malloc(100); //string of length 100
if(string == NULL){
printf("Error\n"); //if malloc() fails
}
if((scanf("%99s", string)) != 1){ //if scanf() fails
printf("Error, Fix it!\n");
exit(1);
}
printf("%s\n",string);
free(string);
return 0;
}
Or, use an array
#include<stdio.h>
#include<stdlib.h>
int main(void){
char string[100];
if((scanf("%99s", string)) != 1){
printf("Error, Fix it!\n");
exit(1);
}
printf("%s\n",string);
return 0;
}
scanf doesn't allocate any memory for string; you need to do this yourself prior to calling the function. Else your program behaviour is undefined.
A simple way would be to refactor to char string[100]; say, and hope that scanf doesn't attempt to read more than 99 characters plus the null terminator.
Later on, you'll realise that hoping is too much to ask, and will end up writing your own I/O functions.
You did not allocate memory to string. Thus, by writing into uninitiated pointer, you invoke undefined behavior.
Before you use string, either you have to allocate memory dynamically using malloc() or family, or define string to be an array, like char srting[32] or something.
Also, FWIW, it is always better to limit your input size by the allocated memory, like
scanf("%31s", string);
to protect from buffer overflow in case of longer-than-expected input.
I need to know whats wrong with this code.
#include<stdio.h>
#include<string.h>
int main() {
char a[50], b[100], c[5000];
char *ret;
//enter first name
gets(a);
//enter secend name
gets(b);
//enter statement
gets(c);
strcat(a,b);
if(strstr(c,a) != NULL) {
printf("found your full name");
} else {
printf("not found your full name");
}
return 0;
}
It does not work when, I use the following lines:
mohamed
ramadan
abdelrhmanamirelbatanonywoofymohamedramadanahmedalyomarelazazyahmedkamelahmedsalemessamelnaggarkhaledhelmy
It should find something, but the programm tells me, that it hasn't.
Point 1
As per the man page of strcat()
char *strcat(char *dest, const char *src);
If dest is not large enough, program behavior is unpredictable
In your case,
strcat(a,b);
a maybe not having enough memory to hold the concatenated string. Possible UB. Change the logic.
Point 2
gets() suffers from buffer overflow issue. Use fgets() instead.
I try to compare my two strings that obtained from my scanf and fscanf. I already figured out what is the content inside the each variable. It both show the same strings, but after I compare with this two string in if statement, it doesn't work and execute else statement instead. What's wrong with my codes ?
int main(void)
{
...
char input[256];
printf("Enter your name: ");
scanf("%s",&input);
fp = fopen(_FILE,"r+");
for(i=0;i<textlines(_FILE);i++)
{
fscanf(fp,"%s %d",stuff[i].name,&stuff[i].salary);
if(input == stuff[i].name)
{
// Update name here
}
else
{
printf("Not Found");
}
}
return 0;
}
== just checks for pointer equality. Use strcmp instead
use the function strcmp in string.h library to compare your strings
As others have said, you need to use strcmp to compare strings (really character arrays). Also, you should not pass the address of name (i.e. &name) to the scanf() function.
You have this:
char input[256];
printf("Enter your name: ");
scanf("%s",&input);
....
if(input == stuff[i].name)
...
More correct code would include the following changes:
char input[256];
printf("Enter your name: ");
scanf("%s", input);
....
if (!strcmp(input, stuff[i].name))
....
You should check the definition and use of stuff[i].name as well. scanf() with a %s format character requires a simple char* parameter. The argument to strcmp() is const char* but using char* is fine and will be automatically promoted.
C is more flexible than other languages in that it allows you to obtain the address of variables. You create pointers to variables in this way. However, a variable declared as an array, such as input is already a pointer in a way. Only by providing an index to you dereference the pointer. Specifically:
char input[256];
input is a pointer to the storage of 256 char's
input can be thought of as a char* variable
input[0] is the first char in the array
input[1] is the second char in the array
input+1 is a pointer to the second char in the array.
input+0 (or simply input) is a pointer to the first char in the array.
&input is not good C form. You can kind of think of this as the address of the array but, in reality, input is already the address of the array. There is a use for such types of double-ly addressed variables but your case is not really one of them. Until you've had some practice with arrays and pointers (and their relationship) the following example might be a bit confusing but it does demonstrate where a char** variable might be used.
int allow_access_to_private_data(char ** data)
{
static char mystring[] = "This is a private string";
if (!data) return -1;
*data = mystring;
return 0;
}
int main(int argc, char* argv[])
{
char* string;
if (!allow_access_to_private_data(&string))
printf("Private data is: %s\n", string);
else
printf("Something went wrong!\n");
return 0;
}