【问题标题】:String interpolation with cpp using strings passed as parameters outputs strange results使用作为参数传递的字符串的 c++ 字符串插值输出奇怪的结果
【发布时间】:2021-05-24 03:48:08
【问题描述】:

我想打印一个报告行,该报告行由作为参数传递给函数的字符串和一个整数组成。在我尝试使用字符串之前它工作得很好。我的理智检查有效,所以这是学习的相当尴尬的一部分。
教训:编译错误和 google 是你的朋友。

void funct (int (*func)(int), int n, string label){
    res = (*func)(n);
    printf("Sanity?\n%s\n%s\n%d\n", "sanity check", "sanity check",42);
    printf("%s\n",label);
    printf("%s(%n) = %d", label, n, res); 

    return 
}

困难的部分起作用(传递函数)。健全性检查有效。最后两张照片没有按我的预期工作。这是输出:

Sanity?
sanity check
sanity check
42
r
r(32000) = 648

在调试器中,label 显示了 Im 传入的值 - “Lookups” - 但它打印的是单个字符,甚至不是字符串的一部分。 (也许在 cmets 让我知道?)

【问题讨论】:

    标签: c++ arrays string char printf


    【解决方案1】:

    已解决:
    它试图告诉我问题
    cannot convert 'std::__cxx11::string' {aka 'std::__cxx11::basic_string<char>'} to 'const char*'

    TL'DR
    char* 不是 string...

    // Unintended Output
    string tester = "foo";
    printf("%s <- not foo\n\n", tester);
    
    // Intended Output
    char* testerc = "foo";
    printf("%s <- foo\n\n", testerc);
    

    结果:

    r <- not foo
    
    foo <- foo
    

    对于函数声明:

    void func(char* stringParam){} 有效,但是
    void func(string stringParam){} 在函数中没有打印出我们想要的内容
    printf("%s", stringParam);

    为什么?
    printf 的字符串插值对%s 使用字符数组,而不是实际字符串。 (也不限于printf,是吗?lmk)

    所以解决方案是 使用 c_str() - &lt;string&gt;.c_str() 为函数参数指定正确的对象类型来转换字符串。如果由于某种原因你不能这样做,也许演员阵容会对你有所帮助。

    如果有人想在microseconds 中为快速函数计时并报告它们的持续时间(s、ms、μs 和 ns 都在chronoduration_cast 中工作),这就是驱动用例:

    int timer (int (*func)(int), int n, char* label){
        auto t1 = std::chrono::steady_clock::now().time_since_epoch();
        (*func)(n);
        auto t2 = std::chrono::steady_clock::now().time_since_epoch();  
        auto dur = std::chrono::duration_cast<std::chrono::microseconds>(t2-t1).count();
    
        printf("Approach: %s: %d μs for %d iterations\n", label, dur, n); 
    
        return dur;
    }
    

    现在正确输出:

    Approach: Lookups: 588 μs for 32000 iterations
    Approach: IF-calcs: 962 μs for 32000 iterations
    

    对于使用任意函数的调用:

        int lookupTime = timer(lookupBuzz, iterations, "Lookups");
        int calcTime = timer(calcbuzz, iterations, "IF-calcs");
    

    读者:有什么更好的计时方法?在前 n 个整数上运行 fizzbuzz 的最快方法应该是什么?保存结果的最佳方法是什么?后者使用基本数组 - results[x]=fizzbuzz(x); - 似乎有限制,这就是为什么我只为 n 使用 32000,但我想使用 10M 作为基准。)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-04-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-07
      相关资源
      最近更新 更多