c++ - 字符串迭代延迟200ms
问题描述
有人可以告诉我这段代码有什么问题吗?
我想以 200 毫秒的延迟显示“a”,例如。数字 3 将在 200 毫秒后显示数字 2 和 1 相同,但我无法编写正确的代码来执行此操作。
#include <iostream>
#include <cstdlib>
#include <string>
#include <windows.h>
using namespace std;
int main() {
int a=3;
do {
cout<<a<<endl;
a-=1;
string tekst = a;
for (int i = 0; i < tekst.length(); i++) { // Czasowe pokazanie napisu//
cout << tekst[i];
cout << tekst[i];
Sleep(200);
}
}
while (a=1);
getch();
}
解决方案
我想以 200 毫秒的延迟显示“a”,例如。数字 3 将在 200 毫秒后显示数字 2 和 1 相同,但我无法编写正确的代码来执行此操作。
在这种情况下,您Sleep
的位置是错误的,因为它是在打印后放置的。您也不需要在打印之前将其转换int
为 a 。s 是开箱即用的完美流媒体。std::string
int
你的do-while
循环也是错误的。while (a=1);
将值分配给1
,a
因此循环将永远持续下去,因为1
将隐式转换为true
.
睡眠 200 毫秒的便携式方法是使用该std::this_thread::sleep_for()
函数,而不是使用Sleep()
它不是标准函数。
它可能看起来像这样:
#include <chrono> // std::chrono::milliseconds
#include <iostream>
#include <thread> // std::this_thread::sleep_for
using namespace std::chrono_literals;
int main() {
for(int a=3; a>0; --a) {
// sleep for 200 ms, the standard way
std::this_thread::sleep_for(200ms);
std::cout << a << std::flush;
// or: std::cout << a << '\n';
}
}
更新不支持<thread>
和的旧版本的 Dev C++ <chrono>
:
#include <iostream>
int main() {
for(int a=3; a>0; --a) {
Sleep(200);
std::cout << a << std::flush;
// or: std::cout << a << '\n';
}
}
推荐阅读
- python - 使用 torch.matmul 将 3d 张量与 2d 矩阵相乘
- angular - 如果日期值小于当前日期,则提交表单?使用 NgModel 和 Angular 9
- deep-learning - 可以结合2个神经网络吗?
- list - Prolog:字符列表 <=> 字符列表列表
- vba - 运行时错误 438 - 无法在 vba 中为 XFA PDF 的空文本框设置 xfa.rawvalue
- c++ - Visual C++ 到 Visual Studio 2019 - 未找到从属 DLL
- flutter - ButtonStyle 填充不同于容器填充
- android - 是否可以从项目的不同版本访问 Realm DB Android?
- javascript - angularjs服务工厂函数不是函数
- c# - 如何为.Net框架中的IAmazonS3服务解决unity.config中的依赖关系