【发布时间】:2019-09-07 12:35:25
【问题描述】:
我将一个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;
}
}
假设我输入了单词溢出,我想要得到以下输出:
Word: Overflow
O
v
e
r
f
l
o
w
我对 C++ 很陌生,而且我的母语不是英语,所以请原谅我的错误。谢谢。
【问题讨论】:
-
为什么要使用指针将
word参数传递给函数? -
@πάνταῥεῖ 这个函数稍后会修改字符串。
-
然后只使用参考。没有必要为此使用指针。
-
直接回答您的问题:
(*word)[i]。(*word)取消引用指针,返回一个字符串变量。[i]返回字符串中的字符。
标签: c++ string pointers pass-by-reference