In C how do I strcmp just the beginning 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:
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;
}