This question already has answers here:
How do I properly compare strings in C?
(10 answers)
Closed 6 years ago.
I am new in C programming. Can you please advise, what's wrong with my code? It looks like the if statement is not working, and instead it's jumping and printing the else statement.
#include <stdio.h>
#include <stdlib.h>
int main()
{
char profession;
printf("what is your profession? \n");
scanf(" %s", profession);
if(profession==“QA”)
{
printf(“Go and Test\n“);
}
else
{
printf("Do whatever you want");
}
return 0;
}
First of all, you can't compare strings like that in C. use strcmp or strncmp instead.
Secondly, in your code, profession is a char, and you want to put a string (several chars) in it. It won't work. You can create a char * (pointer on a char) (without forgetting to malloc() it) or a char [] (a char array).
Firstly, strings in C are array of characters, so you have to declare profession as a pointer, pointing to an array of characters. So that statement will look like this char* profession, secondly, you have to use a method called strcmp(char* a, char* b) that accepts two char pointers. This will return 0 if they are equal. I will include the answer, but I assume there are better ways of writing this code.
int main() {
char* profession;
char* compare = "QA";
printf("What is your profession?\n");
scanf(" %s", profession);
if(strcmp(profession, compare) == 0) {
printf("Go and Test\n");
} else {
printf("Do whatever you want");
}
return 0;
}
Related
This question already has answers here:
How do I properly compare strings in C?
(10 answers)
Closed 4 years ago.
I'm writing a code to better understand if/else statements, but I encountered a problem when trying to validate(?) a string, thanks for any help (C language)
#include <stdio.h>
#include <stdlib.h>
int main(){
char nametype[100];
printf("Enter the name type (firstname/lastname): ");
scanf("%s", &nametype);
script1(nametype);
return 0;
}
void script1(nametype){
char firstname[100];
int age;
char typename[100];
if(nametype == "firstname"){
char typename[100] = "first name.";
}
if(nametype == "lastname"){
char typename[100] = "last name.";
} else {
printf("You must enter the correct parameters! \n");
main();
}
printf("Enter your name: ");
scanf("%s", &firstname);
printf("Enter your age: ");
scanf("%d", &age);
printf("Hey! Your %s is %s, you're %d \n", typename, firstname, age);
}
I expect the code to proceed on to the end after I enter "firstname" or "lastname" in the first input, but instead it always proceeds to go to the else block.
You have a fundamental misunderstanding what the == operator does.
It doesn't compare strings. It compares pointers. If you write
char a[100] = "Hello";
char b[100] = "Hello";
then a == b while compare the pointers. a is a pointer to the array a, b is a pointer to the array b, the pointers are different, the comparison is false.
Use strcmp.
PS. That alone won't make your code work, because you are creating a second variable named "typename" in a nested block. It's a different variable than typename in the outer block, so this will have no useful effect whatsoever.
if(nametype == "firstname"){
char typename[100] = "first name.";
}
In this, nametype is compares to an char array "firstname" ,so you have to use strcmp(str1,str2) function.For use this function, you have to use header. It returns 0 if two strings are equal. Like this
if(strcmp(nametype,"firstname")==0){
// char typename[100] = "first name.";//
}
In the if condition, you have used typename variable which is already declared.So no need to re-declare this variable.
In C, it doesn't support the direct string or char array assignment.So you have to use strcpy(destination,source) function.So the code will be like this
if(strcmp(nametype,"firstname")==0){
strcpy(typename,"first name.");
}
This question already has answers here:
What is a segmentation fault?
(17 answers)
Closed 4 years ago.
Recently i have started working on built-in functions but came up with an error and that is:
Why am i getting segmentation fault for this program
#include<stdio.h>
#include<ctype.h>
int main()
{
char str[50];
int n;
printf("Who is your best friend? ");
scanf("%s",str);
n=isalpha(str);
if(n!=0)
{
printf("Is Alpha");
}
else
{
printf("Invalid Input");
}
return 0;
}
Please help me out...
isalpha()'s prototype is
int isalpha( int ch );
The argument is of type int. But the one that you are passing is of type char * since str is a character array.
Perhaps you meant
unsigned char str;
scanf("%c",&str);
isalpha() returns 0 if its argument is not alphabetic.
And to avoid overflow, you could modify your scanf() to
scanf("%49s",str);
with one character to store the \0 character.
Have a look at this post.
Edit: The argument of isalpha() shouldn't be char. It must be at least unsigned char as explained here. Thanks to melpomene for pointing this out.
This question already has answers here:
why this program doesn't give the expected output? [duplicate]
(2 answers)
Closed 7 years ago.
I'm stuck here trying to understand why this assignement can't work in this way in C. What I'm trying to do is substitute all space occurrences with underscore char. (output: Hi_from_Synchronyze)
I saw that the problem comes when I try to do this..
s[n]='_';
the complete code is this one
#include <stdio.h>
#include <stdlib.h>
char *underscore(char *s, int n);
int main()
{
printf("%s", underscore("Hi from Synchronyze", 0));
return 0;
}
char *underscore(char *s, int n)
{
if(s[n]=='\0')
return s;
else {
if(s[n]==' ') {
s[n]='_';
return underscore(s, n+1);
}
else return underscore(s, n+1);
}
}
I'd like to know what's going on behinde and why this happens, not the solution.
Thank you very much in advance
String literals are read-only, so you can't assign to them.
Make a mutable copy of the string first, something like:
char text[] = "Hi from Synchronyze";
printf("%s", underscore(text, 0));
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
Hi i need help about this:
int t;
t = 1;
char abc[256];
int main() {
scanf("%s", abc);
if(abc == "google") {
printf("%s \n", abc);
system("firefox");
} else
printf("error");
}
it always return error please someone help!
i already tried scanf("%c", &abc); and i rewrote this about 5 times with the same result.
I'm new at this so this can be a very stupid thing.
if(abc == "google") {
This doesn't do what you think it does. This checks whether the pointers to those two strings are numerically equal. They never will be, because abc is allocated in the stack, and "google" is a string literal and therefore has static storage duration.
You should use strcmp like ameyCU points out.
In general, don't use scanf like this, the code you wrote is vulnerable to buffer overflow attacks if someone passes a large string.
You might want to look at this nice post about how to use scanf safely. How to prevent scanf causing a buffer overflow in C?
You can't compare the contents of two character arrays with ==. == will just compare the memory addresses of the arrays (after array-to-pointer decay).
Use strcmp instead:
if (strcmp(abc, "google") == 0) ...
The constant string "google" reside in the .rodata section of your program and if you compile with all warning -Wall you get this warning
google.c:10:12: warning: comparison with string literal results in unspecified behavior [-Waddress]
if(abc == "google") {
and this code is equivalent with
const char* const google_str = "google";
if(abc == google_str)
Here both the string "google" and the address to that string is constant. So you see you are doing a pointer comparison and not a string comparison.
printf("%p == %p\n", abc, google_str);
This code will show you that abc reside on the stack and that google_str reside in the .rodata section. String comparison should be done with
if(0 == strcmp(abc, "google")) {
<code>
if(abc == "google")
</code>
would work in object oriented languages like java and dot net
in c cpp you have to use inbuild library functions of String like strcpy,strcmp
<code> int strcmp(const char *str1, const char *str2) <code>
compares the string pointed to, by str1 to the string pointed to by str2.
So you will modify your code as
#include <stdio.h>
int t;
t = 1;
char abc[256],a[256];
int main()
{
strcpy(a,"google");
scanf("%s", abc);
if( strcmp("abc","google")==0 ) {
printf("%s \n", abc);
printf("firefox");
} else
printf("error");
return 0;
}
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;
}