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));
Related
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;
}
The Question is to take three names as input and check whether the 4th input is the first letter of one of those three names.
*It needs to be only of alpha type and no other.
Sample Input:
#ON SNOW
ARYA STARK
HODOR
#
Output:
NO
My code:
#include <stdio.h>
#include <ctype.h>
int main(){
char s1[100],s2[100],s3[100];
char ch[1];
scanf("%[^\n]s",s1);
scanf("%[^\n]s",s2);
scanf("%[^\n]s",s3);
scanf("%s",ch);
if(isalpha(ch[0]) && (s1[0]==ch[0] || s2[0]==ch[0] || s3[0]==ch[0]))
printf("yes");
else
printf("no");
}
As I figured out that gets() no longer works, I tried scanf("%s",s1);.
But since it does not store the calude after the whitespace " ", I tried this scanf("%[^\n]s",s1);. But the scanning stops at the first name itself.
John Player
NO
What is the way to store multiple strings in a char array without using loops and only using branching??
Now before getting to the specified problem lets see what the actual problem is:
Problem with scanf()
The problem with scanf() is that it is really bad at managing overflows. And in case of chars or char sequences the newline character is read on the press of enter key in the subsequent scanning. There are numerous instances on SO that concern this problem. scanf() leaves the new line char in buffer? and Problems with scanf
Problem with gets()
The biggest drawback is that here you need to know the size of input before-hand. If you know your input extremely well, you may use it (Still I won't recommend). Why is the gets function so dangerous that it should not be used?
Problem with fgets()
There are two really common problems with fgets()
The syntax of fgets() is:
char *fgets(char *restrict s, int n, FILE *restrict stream);`
and generally used like
fgets(char_array,100,stdin)
First problem arises when the input is bigger than the integer n provided in the fgets() second parameter. When the input in the buffer is bigger than n it will strip off 1st n chars and allocate it the char pointer which might be a char array. But what about remaining chars? They still are there in the input buffer and will be allocated to next fgets(). Messing things up.
Second problem is that every time a new line feed is allocated to the end of char sequence when the input is smaller than the int n-1.
But if we think for a while the problems with fgets() can be tackled with a simple trick.
Just check for the last character in the char sequence which has been recently allocated. If it is new line, replace it by NULL. Else we know that the input was more than that int provided inside fgets(). So all we have to do is eat up the remaining chars in the input buffer.
Here is an example:
char str1[5];
char str2[5];
fgets(str1,5,stdin);
if(strlen(str1)>0){//to avoid Undefined Behavior in case of null byte input
if(str1[strlen(str1)-1]=='\n'){
str1[strlen(str1)-1]='\0';
}
else{
while((getchar())!='\n');//eating the remaing chars in the buffer
}
}
fgets(str2,5,stdin);
if(strlen(str2)>0){
if(str2[strlen(str2)-1]=='\n'){
str2[strlen(str2)-1]='\0';
}
else{
while((getchar())!='\n');
}
}
printf("\n1.%s\n2.%s",str1,str2);
You could even convert strings you got using fgets to float and integers using things like strol or sscanf, but beware they may not show independent behavior.
Now coming back to the solution to your problem:
#include <stdio.h>
#include <string.h>
int main(){
char s1[100],s2[100],s3[100];
char ch[2];//make ch atleast 2 char wide
fgets(s1,100,stdin);
if(strlen(s1)>0){
if(s1[strlen(s1)-1]=='\n'){
s1[strlen(s1)-1]='\0';
}
else{
while((getchar())!='\n');
}
}
fgets(s2,100,stdin);
if(strlen(s2)>0){
if(s2[strlen(s2)-1]=='\n'){
s2[strlen(s2)-1]='\0';
}
else{
while((getchar())!='\n');
}
}
fgets(s3,100,stdin);
if(strlen(s3)>0){
if(s3[strlen(s3)-1]=='\n'){
s3[strlen(s3)-1]='\0';
}
else{
while((getchar())!='\n');
}
}
fgets(ch,2,stdin);
if(strlen(ch)>0){
if(ch[strlen(ch)-1]=='\n'){
ch[strlen(ch)-1]='\0';
}
else{
while((getchar())!='\n');
}
}
if(isalpha(ch[0]) && (s1[0]==ch[0] || s2[0]==ch[0] || s3[0]==ch[0]))
printf("yes");
else
printf("no");
return 0;
}
Try fgets.
fgets(s1,100,stdin);
fgets(s2,100,stdin);
fgets(s3,100,stdin);
#include <stdio.h>
int main(){
char s1[100],s2[100],s3[100];
char ch[1];
fgets(s1,100,stdin);// like gets but limited by length
fgets(s2,100,stdin);
fgets(s3,100,stdin);
scanf("%s",ch);
if( (s1[0]>='a' && s1[0]<='z') || (s1[0]>='A' && s1[0]<='Z') ){//ch-alpha?
if(s1[0] == ch[0]){ printf("yes"); }//s1[0] == ch[0] ??
else{ printf("no"); }
}
else
printf("no"); return 0; }
I am trying to code a C program to start specific functions on the OS X El Capitan.
The code looks like this:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char mainchoice;
printf(">>> ");
scanf("%s", &mainchoice);
if (strcmp(&mainchoice, "start ftp") == 0) {
system("ftp");
}
else if (strcmp(&mainchoice, "start say") == 0) {
system("say hello");
}
else {
system("say Error")
}
}
This is just a sample code.
When I run it, it always says error via the say command. What am I doing wrong?
Focus here:-
char mainchoice; //declared as a char
scanf("%s", &mainchoice); //using the %s placeholder which is for string
//for character it is %c
Getting the logic behind your code is you want to enter a String not a character.
Make an array of characters like this:-
char mainchoice[20]; //this can hold your string, one character at one index each of the array
Since, your are using multi word in string comparison("start say")
(strcmp(&mainchoice, "start say") == 0)
scanf does not work for multi words. scanf stops reading from the keyboard as soon as you provide a whitespace, tabs, newline.
For solving that problem, use fgets. It's the best way to read multi words or even whole sentences. Never use gets()! It is vulnerable to buffer overflow!
fgets(mainchoice, 20, stdin);
you are declaring mainchoice as a character rather then a string.
use char mainchoice[10]; to create a string.
and replace scanf("%s",&mainchoice) with fgets(mainchoice, 10, stdin);
size is 10 because you are comparing it with a string of length 9, so(9+1 null=10) 10 are enough.
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.
This question already has answers here:
How can I read an input string of unknown length?
(11 answers)
Closed 4 years ago.
I want to read in an arbitrary number of strings, one at a time, using <stdio.h> in C.
I know that you can do this with integers using:
while (scanf("%d ", &integer))
but I cannot do:
while (scanf("%s", string))
How can I implement the above?
The input is on separate lines.
You usually want to use fgets to read input as strings, especially when you want one line of input to end up as one string.
You can also use fscanf with a scanset conversion to read a line at a time, such as:
char line[100], newline;
fscanf("%99[^\n]%c", line, &newline);
Then you can check whether newline=='\n' to determine whether you've read the entire line successfully, or the line was larger than the buffer you provided.
When you're trying to read line-oriented input, you normally want to avoid "%s" (even with a specified length) though, as this reads white-space delimited tokens, not entire lines.
Use a char array:
char charArray[100];
while (scanf("%s", &charArray))
I guess your problem is to terminate the loop. scanf returns the number of successful scanned elements. In case of a string, also the empty string is successful scanned. Thus, you need another criterion, e.g.
while(scanf("%s",string) && (strlen(string)!=0))
I did not completely understand what you were trying to do from your original question. When you said you wanted to read in an arbitrary number of strings, I took that to mean, you wanted your program to be able to read 0 to n strings. Unfortunately in C, you will either have to cap off the maximum number of strings you would ever want to read in like
#define MAX_NUMBER_OF_STRINGS_TO_READ 25, or get into some sophisticated memory allocation scheme to read a string in and then add it to dynamic memory (returned from malloc).
I took the cap the maximum number of strings approach and wrote the following snippet:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char charArray[5][25] = {0};
int main(int argc, char *argv[])
{
int in_idx = 0;
int out_idx = 0;
printf("\n\n%s\n", "Enter no more than 5 strings, no more than 25 characters long.");
while(fgets (charArray[in_idx], 25, stdin))
{
if('\n' == charArray[in_idx][0])
{
printf("%s\n", "Entry terminated with newline.");
break;
}
in_idx++;
}
for(out_idx=0; out_idx < (in_idx + 1); out_idx++)
{
printf("%s", charArray[out_idx]);
}
printf("\n%s\n", "Program ended.");
return 0;
}
I made the termination character a newline. If I only want two strings, I press Enter when I've entered the second string. I terminated fgets by looking for a '\n' in the first position of the character array.