我将std::string
指针传递给函数,我想使用此指针来访问和修改此字符串中的字符。
现在,我唯一能做的就是使用*
操作符打印我的字符串,但我不能只访问一个字符。我尝试使用*word[i]
,*(word + i)
,其中word
是我的指针,而i
是unsigned 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;
}
}