Aislyn Green
Aislyn Green

Reputation: 11

Write a program that reads a short string and a longer string and checks if the longer string starts with the letters of the short string. Use strncmp

I need help getting this code to work. Could someone tell me how to properly use strncmp and how to get this to work?

This is my code here:

#include <stdio.h>  
#include<string.h>  
int main()  
{  
   char str1[20];   
   char str2[20];    
   int value;   
   printf("Enter the first string right here: ");  
   scanf("%s",str1);  
   printf("Enter the second string right here: ");  
   scanf("%s",str2);  
    
   value=strncmp(str1,str2);  
   if(value==0)  
   printf("Your strings are the same");  
   else  
   printf("Your strings are not same");
  
   return 0;  
  }

This is what my error code is below

main.c:13:27: error: too few arguments to function call, expected 3, have 2
   value=strncmp(str1,str2);  
         ~~~~~~~          ^
1 error generated.
make: *** [<builtin>: main.o] Error 1
exit status 2 ```

Upvotes: -1

Views: 142

Answers (1)

Vlad from Moscow
Vlad from Moscow

Reputation: 311108

Before calling the function strncmp

value=strncmp(str1,str2); 

you should check that str1 is indeed is not less than str2 or vice versa because in your program it is unclear where the user entered a more shorter string and where he entered a more larger string.

But in any case the function strncmp expects three arguments.

At least you have to write

value=strncmp(str1,str2, strlen( str2 )); 

The function is declared like

int strncmp(const char *s1, const char *s2, size_t n);

You could write for example

size_t n1 = strlen( str1 );
size_t n2 = strlen( str2 );

value = strncmp( str1, str2,  n2 < n1 ? n2 : n1 ); 

Also the text in the calls of printf does not satisfy the assignment

printf("Your strings are the same"); 
printf("Your strings are not same");

You are not determining whether two strings are equal. You need to determine whether one string contains another string in its beginning.

Upvotes: 0

Related Questions