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

How can I get a character from a string pointer in C++?

我正在将一个 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++ 的新手,我的母语不是英语,所以请原谅我的错误。谢谢。

你知道你有一个对象,通过引用传递它。然后照常访问对象。

    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;
    }
}