gpt4 book ai didi

c++ - 在 C++ 中通过迭代更新字符串

转载 作者:可可西里 更新时间:2023-11-01 11:36:16 38 4
gpt4 key购买 nike

好的,所以我正在尝试制作一个字符串,以便更新字符串。有点像你有一个字符串“hello”,我希望它像“h”“he”“hel”“hell”“hello”一样更新自己

所以,我有:

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

代码返回如下:

"s“苏”“喝”“ super ”“ super ”

显然在不同的行上,但是当我删除结束行时,造句器就会变得疯狂。它显示类似“spupspppuepr sttrrtrsubstringsubstring”的内容

无论如何我可以在同一条线上更新字符串吗? (并没有完全摧毁它)

最佳答案

您可以在每次迭代时打印回车符 '\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];
}

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

关于c++ - 在 C++ 中通过迭代更新字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10747266/

38 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com