【问题标题】:I need to write a program我需要写一个程序
【发布时间】:2020-07-28 21:40:40
【问题描述】:

任务:编写一个程序,在函数中使用指向字符串的指针来使用结构确定字符串中的字符数。

编译器抛出错误:

error: invalid conversion from 'char' to 'const char*' [-fpermissive]
    8 |     cout << strlen(a);
      |                    ^
      |                    |
      |                    char

这是我的代码:

#include <iostream>
#include <cstring>

using namespace std;

void func(char a)
{
    cout << strlen(a);

}

int main()
{
    struct student
    {
        char name[64];
    };
    student student1;
    cin >> student1.name;
    char* ptr = &student1.name[64];
    func(*ptr);
    return 0;
}

【问题讨论】:

  • Либо перепишите вопрос на английском языке, либо удалите его и задайте на ru.stackoverflow.com
  • strlen 函数需要 pointer 到一个字符,而不是单个字符。你的编译器应该给你一个错误或警告。我建议您将错误和警告级别调到最高。

标签: c++ c-strings strlen function-definition


【解决方案1】:

程序中有几个无效的结构。

你至少得改写

void func( const char *a )
          ^^^^^^^^^^^^^^

char* ptr = student1.name;
func(ptr);

而不是

cin >> student1.name;

最好用

cin.get( student1.name, sizeof( student1.name ) );

此外,您似乎不允许使用标准 C 函数strlen,必须自己编写等效函数。

【讨论】:

  • 您错过了一个:strlen(a),其中a 的类型为char。请参阅 OP 代码中的 void func。 :-)
  • @ThomasMatthews 当函数声明不正确时无关紧要
【解决方案2】:

char a 是单个字符,因此strlen(a) 无效,您需要将指针传递给 func:

void func(const char* a)
{
    cout << strlen(a);

}

int main()
{
    struct student
    {
        char name[64];
    };
    student student1;
    cin >> student1.name;
    char* ptr = student1.name;
    func(ptr);
    return 0;
}

我还更改了&amp;student1.name[64],因为这将获得指向数组中最后一个元素之后的元素的指针,这不是您想要的。

由于我们使用的是 c++,因此我们可以使用 std::string 来使您的代码更简单、更安全:

void func(const std::string& a)
{
    cout << a.size();

}

int main()
{
    struct student
    {
        std::string name;
    };
    student student1;
    cin >> student1.name;
    func(student1.name);
    return 0;
}

【讨论】:

    猜你喜欢
    • 2015-10-29
    • 1970-01-01
    • 2012-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-08
    • 2023-04-03
    相关资源
    最近更新 更多