在C中如何strcmp仅开头2个字符然后连接?

发布于 2024-11-07 08:03:56 字数 215 浏览 1 评论 0原文

在C中如何strcmp仅开头2个字符?然后与另一个字符串连接?像这样的东西:

char s[10];
scanf("%s",s);

/* if i input "cs332" or "cs234", anything start with cs */

if (strcmp("cs",???)==0)
    strcat(s,"by professor");

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");

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

我早已燃尽 2024-11-14 08:03:56
if (strncmp("cs",???, 2)==0) strcat(s,"by professor");

使用strncmp

if (strncmp("cs",???, 2)==0) strcat(s,"by professor");

Use strncmp

忘你却要生生世世 2024-11-14 08:03:56

您正在寻找 strncmp 函数,该函数在功能上与 strcmp 相同,但限制检查的字符数。因此,您将使用长度为 2 的比较字符串和 "cs"。但是,这里还有一些其他问题。

首先,你的缓冲区不够大。当您将文本“by Professor”附加到十个字符的缓冲区时,没有任何字符串适合该缓冲区。

其次,健壮的代码永远不会将scanf与无界字符串格式说明符一起使用:这会导致缓冲区溢出问题。 scanf 系列适用于格式化输入,并且未格式化比用户输入多一点:-)

如果您想要一个强大的输入解决方案,请参阅 我之前的答案之一

第三,您应该始终假设连接字符串可能会溢出缓冲区,并引入代码来防止这种情况发生。您需要添加:

  • 用户输入的字符串的当前长度。
  • 附加字符串的长度(“by Professor”)。
  • 还有一个用于空终止符。

并确保缓冲区足够大。

我将使用的方法是拥有一个(例如)200 字节的缓冲区,使用链接答案中的 getLine() (在下面复制以使该答案独立)且大小足够小(比如 100),那么您可以放心,附加“by Professor”不会溢出缓冲区。


功能:

#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 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;
}

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;
}
空袭的梦i 2024-11-14 08:03:56

为什么不直接比较字符而不是调用strcmp?

例如

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

why not directly comparing characters rather than calling strcmp?

E.g.

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

廻憶裏菂餘溫 2024-11-14 08:03:56

有几种方法可以做到这一点。

字符串比较

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

这是一种简单的方法,因为您无法轻松地将其扩展到稍长的代码(例如长度为 3/4 个字符)。

我想您已经知道应该使用 strncmp() 对吗?

字符串连接

不要使用 strcat。真的。如果您连接两个长度大于 s (目标)大小的字符串,您就会遇到麻烦。考虑使用 snprint() 代替,例如这个:

char str[80];
snprintf(str, 80, "%s by professor", s);

或者,您可以使用 strncat() 正如 Heath 指出的:

char s[80];
strncat(s, " by professor", 80);

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);
绝對不後悔。 2024-11-14 08:03:56

您可以使用 strncmp

编辑:

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'.

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'.
全部不再 2024-11-14 08:03:56

是的,如上所述,strcmp 是首选方法。这里只是用不同的方法来做同样的事情。

#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);

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);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文