初学者的一点指导 [英] A little guidance for a beginner

查看:85
本文介绍了初学者的一点指导的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不明白问题出在我的代码中,我没有看到这样的错误所以我不知道从哪里开始调试它。我现在只学习用C ++编写代码大约一个月了。所以,问题是从const std :: string到char没有合适的转换函数。在这行代码中horses [i] .name = HorseNames [i];在HorseNames下。



:我添加声明



I do not understand the issue is in my code, I have not seen an error like this so I don't know where to start to debug it. I have only been learning to write code in C++ for about a month now. So, the issue is this "No suitable conversion function from const std::string to char exist." in this line of code "horses[i].name = HorseNames[i];" under HorseNames.

edit:: I add the declaration

struct Horse
{
	char name;
	int distance;
	int eventOffSet;
	int ID;
};

        array <Horse, horseCount> horses;
	const string HorseNames[] = { "Black Beauty", "Sea Biscuit", "Bucephalus", 
                                      "Man o War", "Marengo", "Winning Colors" };

	horses[0].ID = 1;
	horses[1].ID = 2;
	horses[2].ID = 3;
	horses[3].ID = 4;
	horses[4].ID = 5;
	horses[5].ID = 6;


 for (int i = 0; i < horseCount; i++)
		{
			horses[i].name = HorseNames[i];
			cout << "These are the Galent Steeds racing today!: "  
                             <<  horses[i].name << endl;
		}





我的尝试:



我用google搜索它并找不到任何东西,我试图将我的const字符串更改为静态字符串,将其重命名为char并且似乎没有任何效果。



What I have tried:

I have googled it and couldn't find anything, I tried to change my const string to a static, renamed it to char and nothing seemed to work.

推荐答案

正如已经建议你应该显示tpyes的声明。



但是,从错误信息中可以假设这样的事情:

As already suggested you should show the declaration of the tpyes.

However, from the error message something like this can be assumed:
std::string HorseNames[MAX_HORSES];
struct {
    char name;
    // Probably more members here
} Horses;
Horses horses[MAX_HORSES];

然后 HorseNames [i] std :: string 无法分配给单个 char ,如 horses [i] .name



您可能希望 Horses.name 成为 std :: string 也是 char 数组。在后一种情况下,您无法使用赋值,但必须复制字符串:

Then HorseNames[i] is a std::string which can not be assigned to a single char like horses[i].name.

You probably want Horses.name to be a std::string too or a char array. In the latter case you could not use an assignment but have to copy the string:

char name[MAX_NAME_LEN];
// Use strncpy or a safe string copy method here to avoid buffer overruns
strncpy(name, HorseNames[i], sizeof(name) / sizeof(name[0]));
// NULL terminate when using strncpy and string is too long
name[sizeof(name) / sizeof(name[0]) - 1] = '\0';


您不能在中存储字符串 char 变量; char 类型只能包含一个字符。你需要一个指向字符串的指针( char * ),或者需要一个字符数组( char [] )作为Jochen建议如上。
You cannot store a string in a char variable; a char type can hold only a single character. You need either a pointer to a string (char*), or a character array (char[]) as Jochen has suggested above.


这篇关于初学者的一点指导的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆