In C how to strcmp just the beginning 2 characters and then concatenate? [duplicate]
In C how do I strcmp just the b开发者_C百科eginning 2 characters? Then concatenate with another string? Something like this:
char s[10];
scanf("%s",s);
/* if i input "cs332" or "cs234", anything start with cs */
if (strcmp("cs",???)==0)
strcat(s,"by professor");
You are looking for the strncmp
function which is functionally identical to strcmp
but limits the number of characters checked. So you would use it with a length of two and the comparison string of "cs"
. But, you have a few other problems here.
First, your buffer is not big enough. There is no string that will fit into a ten-character buffer when you append the text "by professor" to it.
Secondly, robust code will never use scanf
with an unbounded-string format specifier: that's asking for a buffer overflow problem. The scanf
family is meant for formatted input and there is little more unformatted than user input :-)
If you want a robust input solution, see one of my previous answers.
Thirdly, you should always assume that concatenating a string may overflow your buffer, and introduce code to prevent this. You need to add up:
- the current length of the string, input by the user.
- the length of the appending string ("by professor").
- one more for the null terminator.
and ensure the buffer is big enough.
The method I would use would be to have a (for example) 200-byte buffer, use getLine()
from the linked answer (reproduced below to make this answer self-contained) with a sufficiently smaller size (say 100), then you can be assured that appending "by professor" will not overflow the buffer.
Function:
#include <stdio.h>
#include <string.h>
#define OK 0
#define NO_INPUT 1
#define TOO_LONG 2
static int getLine (char *prmpt, char *buff, size_t sz) {
int ch, extra;
// Get line with buffer overrun protection.
if (prmpt != NULL) {
printf ("%s", prmpt);
fflush (stdout);
}
if (fgets (buff, sz, stdin) == NULL)
return NO_INPUT;
// If it was too long, there'll be no newline. In that case, we flush
// to end of line so that excess doesn't affect the next call.
if (buff[strlen(buff)-1] != '\n') {
extra = 0;
while (((ch = getchar()) != '\n') && (ch != EOF))
extra = 1;
return (extra == 1) ? TOO_LONG : OK;
}
// Otherwise remove newline and give string back to caller.
buff[strlen(buff)-1] = '\0';
return OK;
}
Test code:
// Test program for getLine().
int main (void) {
int rc;
char buff[10];
rc = getLine ("Enter string> ", buff, sizeof(buff));
if (rc == NO_INPUT) {
// Extra NL since my system doesn't output that on EOF.
printf ("\nNo input\n");
return 1;
}
if (rc == TOO_LONG) {
printf ("Input too long [%s]\n", buff);
return 1;
}
printf ("OK [%s]\n", buff);
return 0;
}
why not directly comparing characters rather than calling strcmp?
E.g.
if(s[0]=='c' && s[1]=='s'){ ... }
if (strncmp("cs",???, 2)==0) strcat(s,"by professor");
Use strncmp
Several ways to do this.
String comparison:
if ( s[0] == 'c' && s[1] == 's' )
Is the naive way, as you can't expand this easily to slightly longer codes (say 3/4 characters in length).
I guess you've gathered you should be using strncmp()
right?
String Concaternation
Don't use strcat. Really. If you concatenate two strings whose length is greater than the size of s
(the destination) you're in trouble. Consider using snprint()
instead, like this:
char str[80];
snprintf(str, 80, "%s by professor", s);
Or, you could use strncat()
as Heath points out:
char s[80];
strncat(s, " by professor", 80);
You can use strncmp.
Edit:
strcat(s,"by professor");
// s is an array of 10 characters. You need to make sure s is big enough
// to hold the string that needs to be concatenated + to have a terminating
// character '\0'.
Yes, as said, strcmp is the preferred method. Here's just a different way to do the same.
#define CS 29539
char s[80];
scanf("%60s", s);
if( *(short *)s == CS )
if( strlcat(s, " by professor", sizeof(s)) >= sizeof(s) )
fprintf(stderr, "WARNING: truncation detected: %s", s);
精彩评论