通过C ++中的迭代更新string

好的,所以我试图做一个string的事情,以便更新string。 有点像你有一个string“你好”,我希望它有点像“h”“他”“”hel“”地狱“”你好“

所以我有:

#include <iostream> #include <string> #include <windows.h> #include <stdio.h> #include <stdlib.h> #include <conio.h> using namespace std; int main() { system("title game"); system("color 0a"); string sentence = "super string "; for(int i=1; i<sentence.size(); i++){ cout << sentence.substr(0, i) <<endl; } return 0; } 

代码返回如下所示:

“su”“sup”“supe”“super”

很明显,在不同的路线上,但是当我删除最后一行时,句子构build者只是疯狂。 它显示类似“spupsppuepr sttrrtrsubstringsubstring”

有无论如何,我可以更新同一行上的string? (而不是完全摧毁)

您可以在每次迭代时打印一个回车符'\r' ,将光标返回到行首:

 for(int i=1; i<sentence.size(); i++){ cout << '\r' << sentence.substr(0, i); } 

或者按顺序输出每个字符:

 for(int i=0; i<sentence.size(); i++){ cout << sentence[i]; } 

您可能还想为每个循环迭代插入一个很短的延迟来实现打字机效果。

运行你的代码产生这个:

./a.out
ssusupsupesupersuper超级ssuper stsuper strsuper strisuper strinsuper字符串

这正是你告诉它做的。 这和endl一样,但没有换行符。 如果你不想重复所有的字母,你需要遍历字符串本身,而不是通过子字符串。

 using namespace std; int main() { system("title game"); system("color 0a"); string sentence = "super string "; for(int i=0; i<sentence.size(); i++){ cout << sentence[i]; } return 0; } 

我的建议:使用While loop

 #include <stdio.h> #include <iostream> int main() { system("title game"); system("color 0a"); char* sentence = "super string"; while( *sentence ) std::cout << *sentence++; return 0; }