通过C++中的迭代更新字符串

Updating a string through iteration in C++

本文关键字:更新 字符串 迭代 C++ 通过      更新时间:2023-10-16

好的,所以我正在尝试制作一个字符串,以便更新字符串。有点像你有一个字符串"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"苏"嗡"苏佩"超级"

显然在不同的行上,但是当我删除结束行时,句子生成器就会变得疯狂。它显示类似"spupsppuepr sttrrsubstringsubstringsubstring"的内容

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

您可以在每次迭代时'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
苏普超级斯特里超级斯特里超级弦

这正是你告诉它要做的。它与 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;
}