1

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");
jenifer
  • 21
  • 1
  • 1
  • 4

6 Answers6

4

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;
}
Community
  • 1
  • 1
paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
3
if (strncmp("cs",???, 2)==0) strcat(s,"by professor");

Use strncmp

sehe
  • 374,641
  • 47
  • 450
  • 633
3

why not directly comparing characters rather than calling strcmp?

E.g.

if(s[0]=='c' && s[1]=='s'){ ... }

Moses Xu
  • 2,140
  • 4
  • 24
  • 35
2

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);
  • Why not strncat()? Much faster than snprintf(). – Heath Hunnicutt May 14 '11 at 01:39
  • @Heath fair point, it'd work fine. I think I just reached for snprintf first. –  May 14 '11 at 01:48
  • About a year ago, I wrote my own snprintf(). It was a lot easier than I had imagined/feared. It was also educational. The result was less slow due to "format string parsing" than I had assumed prior to writing it. I also didn't support anything more than ASCII/ANSI - sort of K&R sprintf() + the n that makes it snprintf(). I just wanted to share that because I encourage people to write an snprintf() for great fun. – Heath Hunnicutt May 14 '11 at 02:59
1

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'.
Mahesh
  • 34,573
  • 20
  • 89
  • 115
-1

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);
Mel
  • 6,077
  • 1
  • 15
  • 12