Error in string do while [duplicate] - c

This question already has answers here:
How do I properly compare strings in C?
(10 answers)
Closed 5 years ago.
char str[6];
do
{
printf("Enter the string you wanna check:");
scanf("%s", str);
}
while(str != "exit");
Why does this not work?

str will never equal "exit", because you're comparing the addresses of two different sections of memory. You probably want to compare the contents of the strings, for which there is a function strcmp().

"exit" is a char[5] generated by the compiler at some address in the data segment. This address is definitely different from the address of str, as two different objects cannot occupy the same location in memory.
The != operator between expressions of type char[] compares two pointers. These two pointers are the address of "exit" and the address of str, which, as I have already explained, will never be equal.
So, the expression str != "exit" will never evaluate to true. Which brings us to another point: your compiler should have issued a warning about this condition being always false. Which means that you are trying to program without -Wall. Don't do this, you are never going to get very far. Always use the highest warning level, and when you see warnings, always fix them.
To correct the problem, do as user3121023 suggested in a comment, and use strcmp() to compare strings.

The short answer is: it does not work because you must use strcmp(str, "exit") to compare the strings and loop for as long as the return value of strcmp() is not 0.
The long answer is: there are more problems in this little code fragment:
The array into which you read a word is very short and you do not limit the number of characters scanf() is likely to store there. Any user input longer than 5 non space characters will cause undefined behavior.
You do not check the return value of scanf(). A premature end of file, such as redirecting input from an empty file, will cause an infinite loop.
Here is how the code can be written in a safer way:
#include <stdio.h>
int main(void) {
char str[80];
for (;;) {
printf("Enter the string you wanna check:");
if (scanf("%79s", str) != 1 || strcmp(str, "exit") == 0)
break;
}
return 0;
}

As suggested above, use strcmp from the <string.h> header file.
char str[6];
do {
printf("Enter the string you wanna check:");
scanf("%s", str);
} while(!strcmp(str, "exit"));

Try :
#include <stdio.h>
#include <string.h>
int main() {
char str[6];
do
{
printf("Enter the string you wanna check:");
scanf("%s", str);
}
while(strcmp(str, "exit") != 0);
return 0;
}

Related

How on earth to use char and if statements?

I'm a rookie programmer trying to run a simple code on VS code.
#include<stdio.h>
int main()
{
char* a;
printf("Enter a char");
scanf("%s",&a);
if (a = "yes")
{
printf("Number is 30");
}
else if (a = "no")
{
printf("Number is 50");
}
else{
printf("oops");
}
return 0;
}
I guess looking at the code you guys can figure out what I'm trying to do, if the user enters "yes", a specific sentence need to be displayed and similarly for "no".
The problem here is whatever I write in the input, it will always print the first statement, "Number is 30". I've tried running similar codes but ended up with the same output.
If possible, please explain me how to use char,strings,arrays with if-else statements.
There are several misunderstandings in the posted code.
First there is a misunderstanding of char versus string. A char is for instance a single letter, a single special character like ., ;, etc. (see note1) while a string is a serie of chars. So
'y' is a char
"yes" is a string
You print "Enter a char" but from the code it's obvious that you really want "Enter a string".
This leads to the next problem. To input a string using scanf you need to pass a "pointer to char". Your code pass "a pointer to pointer to char" due to the &. Further the passed pointer must point to some memory. So you need:
char a[10]; // Make it an array of char so that it can hold a string
printf("Enter a string, max 9 characters");
scanf("%9s", a); // No & before a and width specifier used to avoid buffer overflow
Now this part
if (a = "yes")
is not the way to compare two strings in C. For that you need the function strcmp - like:
if (strcmp(a, "yes") == 0)
Putting it together it's like:
int main()
{
char a[10];
printf("Enter a string, max 9 characters");
scanf("%9s", a);
if (strcmp(a, "yes") == 0){
printf("Number is 30");
}
else if (strcmp(a, "no") == 0)
{
printf("Number is 50");
}
else
{
printf("oops");
}
return 0;
}
That said, I don't understand why you print stuff like: "Number is 30" but that's kind of irrelevant here.
note1: The type char is actually an integer type, i.e. a number, but the common use is to map these numbers to characters using ASCII encoding.
There are different ways to initialize a variable to access C string.
char *char_ptr = "Hello";
This initializes char_ptr to point to the first character of the read-only string "Look Here".A C string initialized through a character pointer cannot be modified. When a C string is initialized this way, trying to modify any character pointed to by char_ptr is undefined behaviour. An undefined behaviour means that when a compiler encounters anything that triggers undefined behaviour, it is allowed to do anything it seems appropriate.
A more convenient way to define strings that can be modified is to use:
char str[];
This way you can modify any character in the C string
p.s you also need to use strcmp() for the if statement
You can take string input in C using
scanf(ā€œ%sā€, str);
And to compare the string you need to use:
strcmp(str1, "yes");

Why "while" loop does not end when condition is met? [duplicate]

This question already has answers here:
How do I properly compare strings in C?
(10 answers)
Closed 7 years ago.
I have an apparently easy issue but I just cannot get what am I doing wrong.
I've got a code which will test a 60 character entered text in console and if in that text the "terrorist" word appears it will prompt the message "suspect text" and when that word does not appear it would show "nothing suspect".
The text entering "mode" should finish when the word "done" is entered. This seems to be my problem because my while loop just does not want to end.
Any hints?
#include <stdio.h>
#include <conio.h>
#include <string.h>
#include <stdlib.h>
int start_with (char *sir1, char *sir2)
{
int i,j,k;
int len_sir2=strlen(sir2);
char sir3[60]="";
for (i=0;i<=len_sir2;i++)
{
sir3[i]=sir1[i];
}
k=(strcmp(sir2,sir3)) ? 0:1;
return k;
}
int main()
{
char *txt1;
char sir1[60]="", sir2[60]="terorist", sir_test[60]="done";
int i,j,lensir1, contor=0,buf_de_la=0, buf_la;
while (sir1!=sir_test)
{
printf("Enter desired text and press ENTER \n");
gets(sir1);
printf("\n");
buf_la=strlen(sir1);
char *txt1="Nothing suspect";
while (buf_de_la<buf_la-7)
{
char sirbuf[60]="";
j=buf_de_la;
for (i=0;i<=7;i++)
{
sirbuf[i]=sir1[j];
j=j+1;
}
if (start_with(sirbuf,sir2)==1)
{
txt1="SUSPECT text entered!";
break;
}
buf_de_la=buf_de_la+1;
}
printf("%s\n",txt1);
getch();
system("cls");
}
return 0;
}
You should compare C-style strings by using strcmp, like this
while (strcmp(sir1, sir_test) != 0)
This happens because when you do sir1!=sir_test, what you are actually testing is if both character arrays are pointing to the same address in memory, which is not true, since they are two different character arrays located at two different memory addresses.
Instead, what you want to do is compare the characters contained in each variables memory space, and that's what strcmp does: it compares character by character until a null terminating character is found.
Instead of while (sir1!=sir_test), try this: while (strcmp(sir1,sir_test)). strcmp, strcmpi etc. are the proper functions to be used for string comparisons. They are declared under the string.h header file.
The issue is with your comparison while (sir1!=sir_test) which is wrong. It actually compares the addresses of the two strings. You can use strcmp or various other forms of the same function for comparing strings.
A small change which could make your code working is shown below..
do{
printf("Enter desired text and press ENTER \n");
.
.
.
system("cls");
}
while (strcmp(sir1,sir_test));

'Scanf' for a String - Program crashing?

Why is this crashing when I input the string? I don't think I'm reading in the string right but the program gives me an error on the first 'scanf.' The program should be correct but this is C not C++. Most help that I could find was for C++.
//Andrei Shulgach
//April 27th, 2015
/*A string is a palindrome if it can be read forward and backward with the same
meaning. Capitalizations and spacing are ignored.*/
#include <stdio.h>
#include <stdlib.h>
int newStrCmp (const char *string1, const char *string2);
int main()
{
//Local Declarations
int dummy, value;
char string1[100],string2[100];
printf("Please enter the 1st string: ");
scanf_s("%99s", string1[100]);
printf("\nPlease enter the 2nd string: ");
scanf_s("%99s", string2[100]);
//Call Function and get value
value = newStrCmp(string1, string2);
if (value == 0)
printf("The strings are equal.\n");
else
printf("The strings are not equal.\n");
scanf_s("%d",&dummy);//Keep Window Open
return 0;
}
int newStrCmp (const char *string1, const char *string2)
{
//Local Declarations
int value = 0;
while (string1[value] == string2[value])
{
if (string1[value] == '\0' || string2[value] == '\0')
break;
value++;
}
if (string1[value] == '\0' && string2[value] == '\0')
return 0;
else
return -1;
}
You must enable all compiler warnings that you can get from your compiler; the above code shouldn't have compiled.
This:
scanf_s("%99s", string1[100]);
invokes undefined behavior since it indexes outside the 100-character string1 array. Remember that C arrays are indexed from 0. It also fails to comply with scanf_s()'s requirement that the size be specified for all string conversions.
It then probably1 causes more undefined behavior, when scanf_f() interprets a single character as a buffer address where input is to be stored (assuming the call happens, of course).
This is not valid code.
It should simply pass the address of the first character in the array:
scanf_s("%99s", string1, sizeof string1);
Here, string1 is the same as &string1[0]; the name of an array evaluates to the address of its first element in many contexts. We then use sizeof string1 as the third argument to specify the size of the string1 buffer, which is required.
1 You cannot reason about what happens after undefined behavior has happened with any certainty.
The issue is you are 'scanf'ing into index 100 of your length 100 buffer, i.e. out-of-bounds.
scanf_s("%99s", string1);
Also your comparison would be safer as a for loop that ensures value is less than 100, rather than a while loop.
In the future, please include the error message.

using fgets and strcmp in C [duplicate]

This question already has answers here:
strcmp on a line read with fgets
(6 answers)
Closed 9 years ago.
I'm trying to get a string input from the user and then run different functions depending on the input they've entered.
For example, say I asked, "What is your favorite fruit?" and I want the program to comment depending on what they enter...I'm not sure how to do this. Here's what I have so far:
#include <stdio.h>
#include <string.h>
char fruit[100];
main() {
printf("What is your favorite fruit?\n");
fgets (fruit, 100, stdin);
if (strcmp(fruit, "apple")) {
printf("Watch out for worms!\n");
}
else {
printf("You should have an apple instead.\n");
}
}
When I run the program, no matter what I enter, it never does the else statement.
Thanks for your help!
Note two things in your code:
fgets keeps the trailing '\n'. the associated char in fruit should be replaced with a '\0' before comparing with the string "apple".
strcmp return 0 when two strings are the same, so the if clause should be changed based on what you mean.(The fruit and "apple" be equivalent in the if clause)
Standard usage of C main function is int main(){ return 0;}
The revised code:
#include <stdio.h>
#include <string.h>
char fruit[100];
int main() {
printf("What is your favorite fruit?\n");
fgets (fruit, 100, stdin);
fruit[strlen(fruit)-1] = '\0';
if (strcmp(fruit, "apple") == 0) {
printf("Watch out for worms!\n");
}
else {
printf("You should have an apple instead.\n");
}
return 0;
}
Change the if condition to the following:
if(strcmp(fruit,"apple") == 0)
strcmp returns 0 strings if match. You should always compare the result using == operator
strcmp returns 0 if the inputs match, some value>0 if the left is "greater" than the right, some value<0 if the left is "lesser" than the right. So usually you want to simply test for equality with strcmp(...)==0. But there is also the clever version: !strcmp(...). Even if you don't use this style, it's useful to learn to recognize it.
And remember that fgets does not remove the newline character '\n' from the string.

strcmp() thinks that strings arent equal.. but are they? [duplicate]

This question already has answers here:
strcmp on a line read with fgets
(6 answers)
Closed 7 years ago.
For unknown reason, result of running my C program is quite unexpected. I think that it has to be some kind of a beginner mistake, however I can't find out really, where is it.
#include <stdio.h>
#include <string.h>
int main()
{
char string1[50];
char string2[50];
int compare;
puts("Enter two strings: ");
fgets(string1, strlen(string1)+1, stdin);
fgets(string2, strlen(string2)+1, stdin);
compare=strcmp(string1, string2); /* usage of extra variable makes the code more readable but wastes more memory */
printf("%d: ",compare);
if (compare<0) puts("First string is lesser");
else if (compare>0) puts ("First string is bigger");
else puts("Strings are equal");
return 0;
}
And on testing:
Enter two strings:
heheisntthisalongstring
heheisntthisalongstring
1: First string is bigger
------------------
(program exited with code: 0)
Press return to continue
Shouldn't those strings be equal?
fgets(string1, strlen(string1)+1, stdin);
fgets(string2, strlen(string2)+1, stdin);
These are wrong. string1 and string2 are not initialized, and strlen just counts the number of bytes, till hitting \0. In this case, strlen could return any (random non-negative) number.
Use sizeof, instead of strlen here.
Here
char string1[50];
char string2[50];
you dont initialise them, so your initial calls to strlen are unreliable as they are looking for the first null char they find after the start of the array. This could be anywhere and the results of the call may or may not be a true reflection on the size - you just cant rely at all on the results.
string1 is not memset to 0, So strlen(string1) value will not give the expected value (50). strlen will counts the character till it reaches \0. So it may leads to crash also(an undefined behaviour).
Better memset both string1 and string2 like below.
char string1[50] = {0};
char string2[50] = {0};
and also use sizeof operator to get the value 50.
fgets(string1, sizeof(string1), stdin);
fgets(string2, sizeof(string2), stdin);
or else directly go for scanf
scanf("%s", string1);
scanf("%s", string2);
Here have a look at this-strlen
Although the code you are using is not good but you can still get your expected answer by using strncmp giving the 3rd parameter the strlen of a common string variable. Just for fun.
Always initialize your variables or they can lead your application to crash. You can see the examples here- strncmp

Resources