o26*_*110 -1 c++ string pointers pass-by-reference
我正在传递一个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;
}
}
Run Code Online (Sandbox Code Playgroud)
假设我输入单词Overflow,我想要以下输出:
Word: Overflow
O
v
e
r
f
l
o
w
Run Code Online (Sandbox Code Playgroud)
我是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;
}
}
Run Code Online (Sandbox Code Playgroud)