C read line as string [duplicate] - c

This question already has answers here:
How do I properly compare strings in C?
(10 answers)
Closed 7 years ago.
char *word[128];
fgets(word, 128, stdin);
if(word == "hello")
printf("You entered hello as your word.");
So basically I am trying to get user input as a string and then use the following comparison so see if the string the user entered is equal to "hello". however, when compiling this code, it doesn't work. What did I do wrong?
EDIT: So based on feedback so far this is what I have:
char word[128];
fgets(word, 128, stdin);
if(strcmp(word, "Hello") == 0)
printf("match\n");
However, when I compile and run this program and enter Hello it does not print "match".

You need to use strcmp to compare strings.
if(strcmp(word, "Hello") == 0)
printf("match\n");

Use strcmp(char *s1, char *s2) to compare strings.
Also change char *wordto char word[].
fgets, as you used it, reads in characters from stdin until it has read new line, 127 characters or EOF (end of file). The new line is part of the string read in word and so the comparison is not equal.
To illustrate, you need to know that a C-style string is an array of characters ended by the special escape character \0. So you are comparing those two strings hello\n\0 and hello\0; note the newline character in the string read from stdin.
You can overwrite the \n at the 6th position with \0 so your strings compare to equal.
A better, general solution is to simply iterate over the characters of the string and replace the first found \n by \0; this could be a good exercise for you maybe.
== does not compare the strings the way you expect it. It merely compares the addresses of the two objects, which in this case are of course different.

Related

C Arrays - Why is the last character in the array displaying, how do I get it to display only the first 5? [duplicate]

This question already has answers here:
How should character arrays be used as strings?
(4 answers)
Closed 2 months ago.
/* Variables */
int num;
char array[5]; // Array must also include NULL char
char new;
/* Accepting user input */
printf("Please enter 5 characters below:\n");
scanf("%c\r", &array[0]);
scanf("%c\r", &array[1]);
scanf("%c\r", &array[2]);
scanf("%c\r", &array[3]);
scanf("%c", &array[4]);
/* Displaying input as string */
printf("%s", array);
I am trying to create a basic program that creates a string that accepts chars one after the other. I know that arrays start at 0 and end with the null character so I made my array[5] so if I inputted "a" "b" "c" "d" "e" I would get the output string "abcde" plus the null character. Sometimes it works with one set of characters but not another. If I input "q" "w" "e" "r" "t" i might get the output "qwerta". How do I stop it from displaying that last character?
I understand that the reason why this character being displayed is that it is undefined and will show whatever value is at that memory location but I don't know how to fix it.
I have tried to include different escape sequences, putting spaces in the scanf and printf statements but what am I doing wrong?
You have a character array with size 5. You read a character into each of the five elements of the array. This does not leave space for the null character, and you do not explicitly set the last char equal to '\0'. Thus this is not a null terminated string, and printing it as a string with the %s specifier in printf has undefined behavior.

C string comparison [duplicate]

This question already has answers here:
How do I properly compare strings in C?
(10 answers)
Closed 5 years ago.
I ve been coding in C++, completly new in C.
Why doesnt it work? I want to end program by typing exit
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char command[4];
do{
printf( " -> " ) ;
scanf("%c", &command);
}while(&command != "exit");
return 0;
}
Because in C you have to use strcmp for string comparison.
In C a string is a sequence of characters that ends with the '\0'-terminating byte, whose value is 0.
The string "exit" looks like this in memory:
+-----+-----+-----+-----+------+
| 'e' | 'x' | 'i' | 't' | '\0' |
+-----+-----+-----+-----+------+
where 'e' == 101, 'x' == 120, etc.
The values of the characters are determined by the codes of the ASCII Table.
&command != "exit"
is just comparing pointers.
while(strcmp(command, "exit") != 0);
would be correct. strcmp returns 0 when both strings are equal, a non-zero
value otherwise. See
man strcmp
#include <string.h>
int strcmp(const char *s1, const char *s2);
DESCRIPTION
The strcmp() function compares the two strings s1 and s2. It returns an integer less than, equal to, or greater than zero if s1 is
found, respectively, to be less than, to match, or be greater than s2.
But you've made another error:
scanf("%c", &command);
Here you are reading 1 character only, this command is not a string.
scanf("%s", command);
would be correct.
The next error would be
char command[4];
This can hold strings with a maximal length of 3 characters, so "exit" doesn't
fit in the buffer.
Make it
char command[1024];
Then you can store a string with max. length of 1023 bytes.
In general, of want to save a string of length n, you need a char array of
at least n+1 dimension.
You use strcmp, obviously:
while (strcmp(c, "exit"))
What your code does is compare the address of the input buffer with the address of the static string "exit", which of course will never match. You must compare the characters at the pointers.
The orher problem is you have a four byte buffer for a five byte string, the terminator character needs to fit. C is extremely tricky this way, you'll need to allocate a "big enough" buffer for whatever people might type in or the program will immediately crash. Use 1024 or something reasonably big for test programs.
Now I say "obviously" because when writing C code you should have a C standard library reference open at all times to be sure you're using the correct functions and arguments, plus to know what tools you have available.
Multiple issues with the code
You need five chars not four to include the ending null char \0.
You should use %s for inputting string. %c is for characters
You are comparing memory locations (or pointers) in the while loop. You need strcmp for comparing strings.

How to Compare 2 Character Arrays [duplicate]

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

C string - identical, and not matching? [duplicate]

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.

in C: reading input string, finding it in char array

writing another program, it reads a txt file, and stores all the letter characters and spaces (as \0) in a char array, and ignores everything else. this part works.
now what i need it to do is read a user inputted string, and search for that string in the array, then print the word every time it appears. im terrible at I/O in C, how do you read a string then find it in a char array?
#include <stdio.h>
...
char str [80];
printf ("Enter your word: ");
scanf ("%s",str);
char* pch=strstr(fileData,str);
while (pch!=NULL)
{
printf ("found at %d\n",pch-fileData+1);
pch=strstr(pch+1,str);
}
read in the user inputted string as a char array as well (cause strings are basically char* anyway in C)
use a string matching algorithm like Boyer-Moore or Knutt-Morris-Pratt (more popularly known as KMP) - google for it if you like for C implementations of these - cause they're neat, tried and tested ways of searching strings for substrings and pattern matches and all.
for each of these indexOf cases, print the position where the word is found maybe? or if you prefer, the number of occurrences.
Generally, the list of C string functions, found here, say, are of the format str* or strn*, depending on requirements.
One for-loop inside another for-loop (called nested loop). Go through all the letters in your array, and for each letter go through all the letters in your input string and find out if that part of the array matches with the input string. If it does, print it.

Resources