【问题标题】:error C2664: cannot convert argument 1 from 'const char [14]' to 'char'错误 C2664:无法将参数 1 从“const char [14]”转换为“char”
【发布时间】:2020-08-23 09:14:40
【问题描述】:

编程新手。我正在编写一个简单的函数来打印 n 次消息,但我不断收到此错误 C2664: cannot convert argument 1 from 'const char [14]' to 'char'。我无法理解它。

#include <iostream>
#include<string>

using namespace std;
void printNTimes(char msg, int n)// I also tried char *msg
{
    for (int i = 1; i < n; i++) 
    {
        cout << msg;
    }
}

int main()
{
   // char word = "Hello";
    printNTimes("Hello, World.", 5);

}

【问题讨论】:

  • char* msg 不起作用,因为 "Hello, World." 是您无权修改的文字,即您不允许使用非常量指针指向它。你需要一个const 限定符,就像迈克的回答一样。

标签: c++ char


【解决方案1】:

char msg 只能接受一个字符,不能接受字符串。

您应该改用const std::string&amp; msg

const char* msg 也应该可以工作。

同样循环int i = 1的初始化应该是int i = 0打印消息n次。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-11
    • 2021-02-14
    • 2021-03-01
    • 1970-01-01
    • 2014-02-27
    • 1970-01-01
    相关资源
    最近更新 更多