0

我坚持如何从向量中检索字符串。我的代码如下。

在我的.h文件中:

vector<string>cloudsImages;

在我的.m文件中:

cloudsImages = FileOperation::readFile();

for (int i = 0; i < cloudsImages.size(); i++) {

    cocos2d:: CCSprite *cloudImage = CCSprite::spriteWithSpriteFrame(CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName(cloudsImages[i]));
    cloudImage -> setTag(1);
    CCSize winSize = CCDirector::sharedDirector()->getWinSize();
    cloudImage->setPosition(ccp(i,winSize.height / 2));
    this -> addChild(cloudImage);

} 

尝试从向量访问字符串时,出现以下错误:

没有可行的std::basic_string<char>转换const char *

在此处输入图像描述

如何从此向量中检索字符串?

4

1 回答 1

4

在这一行中,

cocos2d:: CCSprite *cloudImage = CCSprite::spriteWithSpriteFrame(CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName(cloudsImages[i]));

而不是cloudsImages[i],使用cloudsImages[i].c_str(). 它需要一个 const char*,这是 .c_str() 返回的内容。

所以你的线变成

cocos2d:: CCSprite *cloudImage = CCSprite::spriteWithSpriteFrame(CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName(cloudImages[i].c_str()));

C++ 中的字符串与 C 风格的字符串略有不同。在 C 中,字符串只是一个字符数组,以空字符 '\0' 结尾。char例如,字符串“Hello”由长度为 6的 ' 数组表示(char每个字符为 1,'\0' 为 1)。

在 C++ 中,string类是这个基本数组的包装器。包装器允许您对字符串执行操作(例如比较两个字符串、将一个字符串替换为另一个字符串等)。该类包含一个 C 风格的字符串,它仅用于保存字符。

您的函数需要一个 C 风格的字符串。要从 C++ 字符串中获取它,请使用 c_str() 函数,它是 string 类的成员。

于 2013-03-30T08:00:17.053 回答