通过C++中的迭代更新字符串
Updating a string through iteration in C++
好的,所以我正在尝试制作一个字符串,以便更新字符串。有点像你有一个字符串"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;
}
相关文章:
- 字符串变量未更新 c++
- 为什么字符串没有更新并且最终没有打印任何内容
- 返回字符串vs通过引用传递字符串以更新值
- 实时更新控制台中的字符串内容
- 将字符串转换为 XML 并使用提升更新值字段
- 字符串不会在拆分上更新其值
- 更新:正在输出内存位置,而不是所需的字符串
- 通过引用传递 std::string 不会更新调用函数中的字符串值
- MFC SDI在更改属性时从INI读取并更新视图字符串
- 在C 中更新字符串的一部分
- 如何更新函数中的C++字符串
- 当我在C++中字符串更新对象记录时,用垃圾值更新了文件
- SSE4.1自动在更新的gcc上进行字符串比较
- C++ 总线错误:尝试解析和更新字符串时出现 10
- 通过C++中的迭代更新字符串
- C++分配后字符串大小未更新
- 如何使用tntdb类来更新Sqlite数据库中的字符串值
- 如何使用c++在between字符串中替换更新后的值
- 无法更新QTableWidget中的字符串
- 通过字符串流更新 int