如何从C ++中的字符串指针获取字符?

问题描述 投票:-1回答:1

我将std::string指针传递给函数,我想使用此指针来访问和修改此字符串中的字符。

现在,我唯一能做的就是使用*操作符打印我的字符串,但我不能只访问一个字符。我尝试使用*word[i]*(word + i),其中word是我的指针,而iunsigned int

现在我有这个。

#include <iostream>

void shuffle(std::string* word);

int main(int argc, char *argv[])
{
    std::string word, guess;

    std::cout << "Word: ";
    std::cin >> word;

    shuffle(&word);
}

void shuffle(std::string* word)
{
    for (unsigned int i(0); i < word->length(); ++i) {
        std::cout << *word << std::endl;
    }
}

让我说我输入Overflow这个词,我希望得到以下输出:

Word: Overflow
O
v
e
r
f
l
o
w

我对C ++很陌生,我不是英语母语人士所以请原谅我的错误。谢谢。

c++ string pointers pass-by-reference
1个回答
5
投票

如您所知,您有一个对象,请通过引用传递它。然后像往常一样访问对象。

    shuffle(word);
}

void shuffle(std::string& word) // Not adding const as I suppose you want to change the string
{
    for (unsigned int i = 0; i < word.size(); ++i) {
        std::cout << word[i] << std::endl;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.