gpt4 book ai didi

c++ - 如何将字符串添加到 char 元素的二维数组中?

转载 作者:太空狗 更新时间:2023-10-29 20:47:30 25 4
gpt4 key购买 nike

我有以下用 C++ 编写的程序:

#include <iostream>

using namespace std;

int main()

{
int age[5];
char name[5][10];

age[0]=10;
age[1]=20;
age[2]=30;
age[3]=25;
age[4]=40;

name[0]="abc";
name[1]="abc";
name[2]="abc";
name[3]="abc";
name[4]="abc";

cout<<name[0]<<" is "<<age[0]<<"years old";
cout<<"\n";
cout<<name[1]<<" is "<<age[1]<<"years old";
cout<<"\n";
cout<<name[2]<<" is "<<age[2]<<"years old";
cout<<"\n";
cout<<name[3]<<" is "<<age[3]<<"years old";
cout<<"\n";
cout<<name[4]<<" is "<<age[4]<<"years old";
cout<<"\n\n";

system("PAUSE");

}

当我编译并运行它时,出现以下错误:

error C2440: '=' : cannot convert from 'const char [3]' to 'char [10]' There is no context in which this conversion is possible

error C2440: '=' : cannot convert from 'const char [2]' to 'char [10]' There is no context in which this conversion is possible

error C2440: '=' : cannot convert from 'const char [2]' to 'char [10]' There is no context in which this conversion is possible

error C2440: '=' : cannot convert from 'const char [2]' to 'char [10]' There is no context in which this conversion is possible

error C2440: '=' : cannot convert from 'const char [2]' to 'char [10]' There is no context in which this conversion is possible

我在 Windows 7 下运行 MSVC 2008。我尝试了很多可能的解决方案,但未能解决这个问题。任何帮助将不胜感激,

最佳答案

您正在处理 name 数组,就好像它是这样定义的:

char *name[5];

因此要么以这种方式定义它,要么使用以下代码来填充它:

strcpy(name[0], "abc");
strcpy(name[1], "abc");
strcpy(name[2], "abc");
strcpy(name[3], "abc");
strcpy(name[4], "abc");

我更喜欢前一种选择。关键是您正在尝试将 char * 分配给 char [] ,这就是 strcpy 的用途。鉴于您在这种情况下无论如何都在操作初始化的 C 字符串,您最好在整个代码中处理 char *

关于c++ - 如何将字符串添加到 char 元素的二维数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5451676/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com