相关疑难解决方法(0)

如何正确比较字符串?

我试图让一个程序让用户输入一个单词或字符,存储它,然后打印它,直到用户再次键入它,退出程序.我的代码看起来像这样:

#include <stdio.h>

int main()
{
    char input[40];
    char check[40];
    int i=0;
    printf("Hello!\nPlease enter a word or character:\n");
    gets(input);
    printf("I will now repeat this until you type it back to me.\n");

    while (check != input)
    {
        printf("%s\n", input);
        gets(check); 
    }

    printf("Good bye!");


    return 0;
}
Run Code Online (Sandbox Code Playgroud)

问题是我不断打印输入字符串,即使用户输入(检查)与原始(输入)匹配.我比较错误吗?

c string strcmp

168
推荐指数
6
解决办法
41万
查看次数

为什么这个版本的strcmp更慢?

我一直在尝试strcmp在某些条件下提高性能.但是,遗憾的是,我甚至无法实现普通的vanilla strcmp以及库实现.

我看到了一个类似的问题,但答案说差异来自编译器优化掉字符串文字的比较.我的测试不使用字符串文字.

这是实现(comparisons.cpp)

int strcmp_custom(const char* a, const char* b) {
    while (*b == *a) {
        if (*a == '\0') return 0;
        a++;
        b++;
    }
    return *b - *a;
}
Run Code Online (Sandbox Code Playgroud)

这是测试驱动程序(driver.cpp):

#include "comparisons.h"

#include <array>
#include <chrono>
#include <iostream>

void init_string(char* str, int nChars) {
    // 10% of strings will be equal, and 90% of strings will have one char different.
    // This way, many strings will share long prefixes …
Run Code Online (Sandbox Code Playgroud)

c++ string performance

23
推荐指数
2
解决办法
1880
查看次数

如何检查`strcmp`是否失败?

那么这个问题就是关于C和C++的问题strcmp.

我遇到了这个链接:C库函数 - strcmp().

在这里,它解释了返回值strcmp.我知道每个功能,无论多么安全,都会失败.因此,我知道甚至strcmp可能在某个时候失败.

此外,我遇到了这个问题,也解释了返回值strcmp.经过大量搜索,我找不到一个解释如何检查是否strcmp会失败的网站.

我首先想到它会返回-1,但事实证明,如果第一个字符串较小,它会返回数字<0.那么有人可以告诉我如何检查是否strcmp失败.

编辑:好吧,我不明白strcmp没有失败的意义.函数失败的方法有很多种.例如,在一条评论中,写道如果堆栈没有扩展,可能会导致堆栈过低.没有任何语言的程序是绝对安全的!

c c++ strcmp

-21
推荐指数
2
解决办法
488
查看次数

标签 统计

c ×2

c++ ×2

strcmp ×2

string ×2

performance ×1