【问题标题】:Pass a c style string to a function C++将 c 样式字符串传递给函数 C++
【发布时间】:2013-01-16 06:04:09
【问题描述】:

我已经编写了一个函数来反转 c 样式字符串,如下所示

void reverse1(char* str) {
    char* str_end = strchr(str, 0);
    reverse(str, str_end);
}

并使用此函数打印反转的字符串

void print(char* str) {
    for (int i=0; i!=sizeof(str); ++i) {
        cout << int(*(str+i)) << '\t';
    }
    cout << endl;
}

反转后,打印结果为: 103 110 105 114 116 115 0 0 会有一个额外的 0。 我不知道这是为什么。希望可以有人帮帮我。 非常感谢!

【问题讨论】:

  • sizeof(str) 是指针的大小。我建议只使用std::reverse
  • 我很惊讶它工作得这么好,sizeof(str) 应该只是指针的大小,而不是你想象的字符串的长度。
  • 不确定,但可能是\0 而不是0
  • sizeof(str) 应该是 strlen(str),并且循环应该以这种方式工作:for(int i = 0; i &lt; strlen(str); i++){ } 据我所知,您的程序根本不应该工作。
  • @randomp 使用strlen( str ) 获取字符串长度

标签: c++ string


【解决方案1】:

表达式sizeof(str) 在 64 位平台上的结果为 8。因此,您会在标准输出中获得 8 个数字。

在使用 C++ 编程时,您应该尝试使用 std::string。如果你坚持使用 C 风格的字符串,你可以把输出写成:

void print(char* str) {
    for (int i=0; i<=strlen(str); ++i) {
        cout << int(*(str+i)) << '\t';
    }
    cout << endl;
}

void print(char* str) 
{
    do {
        cout << int(*str) << '\t';
    } while (*str++);
    cout << endl;
}

【讨论】:

  • @qPCR4vir "" 是一个以零结尾的字符串,你得到一个 0。
  • 您的 i != strlen 版本不打印 0/NUL 终止符,而 do { } while () 版本可以。
  • 但是在你测试一个超过这些 0 的时候?
  • 同时增加str可以解决这个问题吗?
【解决方案2】:

正如@harper所说的

在 C++ 中编程时应该尝试使用 std::string

如果是这样,(对我来说)打印反向字符串并查看每个字符代码的最简单方法是

std::copy( str.rbegin(), str.rend(), std::ostream_iterator< int >( std::cout, "\t" ) );

std::copy( str.rbegin(), str.rend(), std::ostream_iterator< char >( std::cout, "\t" ) );

查看每个角色本身

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-09-09
    • 2019-09-28
    • 2013-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-27
    相关资源
    最近更新 更多