1

嘿,伙计们,我创建了一个游戏,在它拥有的代码中while(true),每次输入一个新字符串时,问题是如果我第一次写abc,然后在第二个循环abcd中,然后abc它保存最后一个 d,我试过了str.clear(),我试图把\0它,我试图str = "";,我尝试了一切,它仍然是一样的。

这是一些代码:

    std::string whoplayed;
int res = getPlayersNames();
if(res == -1)
    return;
std::cout << "ok " << splayername << " please start: (Starting from south) S->N->S->N...." << std::endl;
std::string temp = "";
std::string playername = "";
while(true)
{
std::getline(std::cin,temp);
for(int i=0;i<(signed)temp.size();i++)
    {
        if(temp[i] != ':')
        {
            playername[i] = temp[i];
        }
        else break;
    }

    char c;
    for(int i=0;i<(signed)temp.size() ; i++)
    {
        if(temp[i] == ':' && temp[i+1] == ' ')
        {
            c = temp[i+2];
            break;
        }
        else
        {
            continue;
        }
    }

这是代码的一部分..我不能全部发布..当我在第三个循环中使用输入 abc、abcd、abc 打印 playername(确保格式正确,我不需要这样)它保存最后一个 d

4

2 回答 2

1

要清除 std::string 使用

std::string sStr;
sStr.clear();

要将字符串 temp 中的所有字符复制到字符串 playername,您可以使用 string::find_first_of(...) http://www.cplusplus.com/reference/string/string/find_first_of/结合 std::copy http:/ /www.cplusplus.com/reference/algorithm/copy/

于 2015-04-07T12:30:55.923 回答
1

这对我有用。

string test;
test = "hello";

cout << test << endl;

test = "";
test = "abc";

cout << test << endl;
于 2016-08-22T11:01:28.357 回答