Reputation: 1
I need help optimizing the code below, it's been a while since I coded in C and something has changed since then.
Write a program that asks for a name that compares to those that it has as elements of a character array and greets or announces that she is "stranger".
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(){
char who[110];
char names []="Sam John Tom Sophia Jane Mary ";
printf("Enter a name: ");
gets(who);
char *ptr=strstr(names, who);
printf("\n%s\n",who);
if (ptr != NULL)
{
printf("We know '%s'\n", who);
printf("Hello %s", who);
}
else
{
printf("We don`t know '%s'\n", who);
printf("%s is a STRANGER!!", who);
}
return 0;
}
Upvotes: 0
Views: 737
Reputation: 310970
You can use standard function fgets
. For example
fgets( who, sizeof( who ), stdin );
who[ strcspn( who, "\n" ) ] = '\0';
The function can append the new line character '\n'
to the entered string that you need to remove before using the function strstr
.
Alternatively you can use function scanf
the following way
scanf( "%109[^\n]", s );
In this case the new line character '\n'
will not be read in the character array.
if you need to enter only one word then you can use scanf
like
scanf( "%109s", who );
As for your approach then in general it is incorrect. For example the user can enter the word "Jo" and the function strstr
will return a non-null pointer.
It is better to use an array of pointers to string literals like
const char *names[] = { "Sam", "John", "Tom", "Sophia", "Jane", "Mary" };
and then in a loop to check whether the entered string coincides with a string literal in the array.
For example
const char *names[] = { "Sam", "John", "Tom", "Sophia", "Jane", "Mary" };
const size_t N = sizeof( names ) / sizeof( *names );
//...
size_t i = 0;
while ( i != N && strcmp( names[i], who ) != 0 ) i++;
if ( i != N )
{
printf("We know '%s'\n", who);
printf("Hello %s", who);
}
else
{
printf("We don`t know '%s'\n", who);
printf("%s is a STRANGER!!", who);
}
Upvotes: 2