This question already has answers here:
How do I properly compare strings in C?
(10 answers)
Closed 8 years ago.
I have a small problem using gets function and a simple if expression.
It has to check whether the input is correct or no, in this case should be: !S
char checkCommand[5];
gets(checkCommand);
if(checkCommand=="!S")....;
else puts("Invalid command!");
How come I never end up to get true value for the expression,
even if I type !S ? Thanks for all answers!
Because you do not compare strings in C like this: (checkCommand=="!S")
To compare strings, you should use strcmp or strncmp or memcmp functions.
Example: In your case you use it like this:
if (strncmp(checkCommand, "!S", 5) == 0)
To read more about these functions, visit this link and similar.
You should also have noticed a warning "gets is dangerous..." something like this. You should avoid using gets and use fgets instead. The reason is well explained by Chris Jester-Young in his answer.
C has no strings; it has character pointers, and == simply compares the pointers. Use strcmp or strcasecmp (if your system has that) to compare strings. Note that strcmp returns 0 when the strings compare equally.
Also, avoid using gets. If a user enters a string longer than 4 characters (in your case), other parts of your memory will start getting scribbled on. Instead, prefer to use fgets, which allows you to specify the size of your input buffer.
You must use strcmp() function to compare two strings in c
int ret;
ret=strcmp(checkCommand,"!s");
if(ret!=0)
{
printf("Invalid Command");
}
Replace if(checkCommand=="!S") -> if(!strcmp(checkcommand,"!S"))
Related
I'm writing a program with C and this is one of my functions:
void group3()
{
char select[5];
printf("\nDetails etc.");
printf("\nPlease confirm Yes/No if you would like to subscribe:");
scanf("%s", select);
if (select == "Yes")
printf("Good.");
else
{
printf("Alright.");
main();
}
}
But when I try to compile and debug the program, a warning called "return value ignored: 'scanf'" appears. I noticed that the warning appears when I'm running scanf for integers too but the program still works for integers. However, when I try to scanf for strings, it doesn't work. I've tried using getchar() but the same warning occurs for getchar(). I've also tried using scanf_s but the same problem appears when I try to scanf_s for strings. I've also defined _CRT_SECURE_NO_WARNINGS in my program. Would really appreciate it if someone could explain to me how I can eliminate this warning from occurring/get the scanf or getchar to work with strings.
edit: thanks to some helpful users i found out that the problem isn't because the string wasn't read, but because i cannot compare strings using the if statement this way. the answer is in the comment section and i can't select it as the correct answer to this but this question is closed. thank you :)
The problem is that the return value of scanf() is ignored, so don't ignore that to eliminate the warning.
scanf() returns the number of data read on success and negative number on error, so it is useful to check if it successfully read required things.
Example:
if (scanf("%4s", select) != 1) {
fputs("read error\n", stderr);
exit(1);
}
Also it is good to read the length to read to avoid buffer overrun.
This is also done in the above example.
One more point is that select == "Yes" is not a correct way to compare strings in C.
This is comparing pointers and it won't be true because the array and the string literal are stored in differenct places in memory.
strcmp() function from string.h is useful to compare strings.
This question already has answers here:
How do I properly compare strings in C?
(10 answers)
Closed 6 years ago.
How do I compare these two character arrays to make sure they are identical?
char test[10] = "idrinkcoke"
char test2[10] = "idrinknote"
I'm thinking of using for loop, but I read somewhere else that I couldnt do test[i] == test2[i] in C.
I would really appreciate if someone could help this. Thank you.
but I read somewhere else that I couldnt do test[i] == test2[i] in C.
That would be really painful to compare character-by-character like that. As you want to compare two character arrays (strings) here, you should use strcmp instead:
if( strcmp(test, test2) == 0)
{
printf("equal");
}
Edit:
There is no need to specify the size when you initialise the character arrays. This would be better:
char test[] = "idrinkcoke";
char test2[] = "idrinknote";
It'd also be better if you use strncmp - which is safer in general (if a character array happens to be NOT NULL-terminated).
if(strncmp(test, test2, sizeof(test)) == 0)
You can use the C library function strcmp
Like this:
if strcmp(test, test2) == 0
From the documentation on strcmp:
Compares the C string str1 to the C string str2.
This function starts comparing the first character of each string. If
they are equal to each other, it continues with the following pairs
until the characters differ or until a terminating null-character is
reached.
This function performs a binary comparison of the characters. For a
function that takes into account locale-specific rules, see strcoll.
and on the return value:
returns 0 if the contents of both strings are equal
This question already has answers here:
Issue with main arguments handling
(3 answers)
Closed 7 years ago.
I am fairly new to C, so am not overly familiar with it's syntax, however I have debugged my code and researched for the correct syntax, and it seems to be correct, I have also changed the scope of the variables to see if this was causing the error.
The if statement should compare two variables, which both hold strings, I have even printed both the variables out to ensure they are the same, however it is still skipping straight to the else section of the if statement. Can anyone give me any pointers on why it will not run the if statement, it just skips straight to 'incorrect'.
The correctWord variable is defined at a different section in the code.
Find full code here.
-UPDATE-
I have now updated the syntax of the code, however it is still returning false.
char correctWord[20];
void userGuess(){
char userWordGuess[20];
printf("Anagram: ");
printf(anagramWord);
printf("Your Guess: ");
scanf("%s",userWordGuess); //Reads in user input
printf(correctWord);
printf(userWordGuess);
if(strcmp(userWordGuess, correctWord) == 0){
printf("Congratulations, you guessed correctly!");
}else{
printf("Incorrect, try again or skip this question");
}
}
You cannot compare strings in C using ==, because this compares the addresses of the strings, not the contents of the string. (which you certainly don't require, and obviously, the addresses of the two strings are not equal too.)
C has a pretty nice function for it : strcmp() which returns 0 if both the strings are equal.
Try using this in your if condition:
if (!strcmp(userWordGuess,correctWord))
{
//Yay! Strings are equal. Do what you want to here.
}
Be sure to #include <string.h> before using strcmp().
In C, you can't compare strings using ==. You will end up comparing the addresses of the strings, which is not the same.
You need to call the strmcp() function, which will return 0 if its arguments (two strings) are equal.
So the code should be if(strcmp(userWordGuess, correctWord) == 0).
You're comparing addresses of different arrays, which will always be unequal.
You need to use strcmp or some other strings library function to compare strings character by character.
userWordGuess == correctWord will compare the pointers (i.e. the locations in memory of the arrays), which are probably not equal.
For string comparision in C, use strcmp (or strncmp):
if (!strcmp(userWordGuess, correctWord)){
/*Strings are equal*/
Use
if(strcmp(userWordGuess, correctWord) == 0) // strings are equal
{
printf("Congratulations, you guessed correctly!");
}
else // not equal
{
printf("Incorrect, try again or skip this question");
}
if both string are equal than if condition will run. otherwise it wil run else
The strings are not first-class citizens in the C language. The strings are represented as either arrays of characters or pointers to such arrays.
In both cases, the variable you use to access the string is a synonym for the address in memory of the first character of the string.
What you compare with userWordGuess == correctWord is not the strings but their addresses in memory. Since userWordGuess and correctWord are two different arrays of characters, their addresses in memory are always different and their comparison will always produce FALSE.
In order to compare the actual string values you have to use the standard function strcmp() or one of its variants (find them at the bottom of the documentation page).
Change in the code:
/** Need to include the header that declares the strcmp() function */
#include <string.h>
char correctWord[20];
void userGuess(){
char userWordGuess[20];
/** stripped some lines here ... */
/** compare the strings, not their addresses in memory */
if (strcmp(userWordGuess, correctWord) == 0) {
/** the rest of your code */
What you are doing here is comparing two pointers. userWordGuess and correctWord point each to the beginning of an array of characters (which is what you defined at the beginning of your example code).
So if you want to compare the two arrays of chars you can use the strcmp function defined in string.h
It is important that you learn the relation between arrays and pointers. Pointer arithmetic is as well important here. Check this out: Arrays, Pointers, Pointer Arithmetic
This question already has answers here:
Why is "a" != "a" in C?
(11 answers)
Closed 8 years ago.
I have a code below that asks if the user wants to retry or not. If the user enters no, the program will terminate. My code doesn't work and the loop still runs even if the input is "no"
#include<stdio.h>
int main()
{
char x[5];
do
{
printf("would you like to try again?");
scanf("%s",&x);
}
while(x != "no");
getch(); return 0;
}
I've tried adding a space in the scanf just like for characters to consume the newline but it also doesn't work. sorry for a very noob question.
You should use strcmp() to compare strings.
do { ... } while (strcmp(x, "no") != 0);
The issue of comparing an char array has been addressed by other answers and comments. There is another possible problem with an array of 5 elements being overrun by an input of "Yes, I would like to try again." Using %4s will limit scanf. Another option would be to use fgets ( x, sizeof ( x), stdin); fgets will include the newline so the comparison would be to "no\n" instead of "no".
#include<stdio.h>
#include<string.h>
int main()
{
char x[5];
do
{
printf("would you like to try again?");
scanf("%4s",x); // %4s prevent overrun. x is array, no need for &
}
while( strcmp ( x, "no") != 0);
getchar();
return 0;
}
You can't compare two strings by using !=, since the value of x is actually the memory address of your string.
You must include string.h and use the strcmp() function. (Take a look at the doc.)
x is just stand for the base address of the array while "no" is just stand for the address of the literal string [no\0]. So x != "no" is comparing two addresses which is always false.
You should use strcmp in the standard C lib.
Your problem is at the condition of the while loop. x is an array that contains characters. Using the x!="no" you are checking the base address of the array (to be more specific when you drop the brackets the compiler translate that as a pointer that points at the array x at the cell x[0,0]).
So the best solution and the easiest one to your problem is to use the strcmp function. The strcmp stands for string compare. This function compares character by character between two strings using the ascii code. The strcmp function returns zero only if the two strings are the same.So at your case you should use something like:
while(strcmp(x,"no")!=0){
....
This question already has answers here:
Using the equality operator == to compare two strings for equality in C [duplicate]
(9 answers)
Closed 9 years ago.
Got a small problem with C. Restricting myself to simple C (i.e. OS instructions), and two strings seem to not be the same. Here is my code:
char inputData[256];
int rid;
rid = read(0,inputData,256);
// Strip input
char command[rid];
int i;
for (i = 0; i<=rid-2; i++) {
command[i] = inputData[i];
}
command[rid-1] = '\0';
if (command == "exit") {
write(1,"exit",sizeof("exit"));
}
Now, if a user enters "exit" into the terminal when queried and hits enter, the if for detecting "exit" never gets run. Any ideas?
Thanks,
EDIT: I am commiting to git as I go, so the current version can be found at github.com/samheather/octo-os. It's very obviously not complete code, but it demonstrates the problem.
You can't compare strings with ==. You need to use strcmp.
if (strcmp(command, "exit") == 0) {
C strings are actually character arrays. You can think of "command" as a pointer to the first character. You want to compare every character in the string, not just the location of the first characters.
You should use strcmp to compare strings in C.
if(strcmp(command, "exit") == 0) //strcmp returns 0 if strings are equal
To quote:
A zero value indicates that both strings are equal. A value greater than zero indicates
that the first character that does not match has a greater value in str1 than in str2.
a value less than zero indicates the opposite.
As it stands right now, you're comparing the address of command with the address of the string literal "exit", which pretty much can't be the same.
You want to compare the contents, with either strcmp, or (if "only OS instructions" means no standard library functions) an equivalent you write yourself that walks through the strings and compares characters they contain.
As others said, == doesn't work with strings. The reason is that it would compare the pointers given.
In the expression
command == "exit"
command is a pointer to your array variable, while "exit" is a pointer to that string which resides in read-only data space. They can never be identical, so the comparison always is false.
That's why strcmp() is the way to go.
Use strcmp from the standard library.