[英]C++ Print one letter at the time. How to?
Let's say i have a string, that contains a message. 假设我有一个包含消息的字符串。 If i want to print it on the screen, i just can do
cout<<string, or cout<<"Hello!"
如果我想在屏幕上打印它,我可以执行
cout<<string, or cout<<"Hello!"
. 。 But the message gets printed all at once.
但是消息立即全部打印出来。
So what i am looking for is a function that takes a message and a number as input variables, and prints the message one letter at the time, using the number as delayer. 因此,我正在寻找的功能是将一条消息和一个数字作为输入变量,并使用数字作为延迟器,一次将消息打印一个字母。
Like this: 像这样:
void slow_print("Hello!", 5);
This means print each letter with 5 seconds of delay between them. 这意味着打印每个字母之间会有5秒钟的延迟。
Unfortunately, i have no idea how to do that (except for the delay, wich you can do with the Sleep() function), and so i came up with this ugly looking solution: 不幸的是,我不知道该怎么做(除了延迟,可以使用Sleep()函数),所以我想出了一个难看的解决方案:
string A = "A", B = "B", C = "C", D = "D", E = "E" .... //etcetera...
Then i would declare a vector, wich contains those letters. 然后,我将声明一个向量,其中包含这些字母。 So then i could do a for loop, for instance, that prints one vector cell at the time.
因此,例如,我可以执行一个for循环,该循环将同时打印一个矢量单元。
vect[dimension] = { H,e,l,l,o,_,h,o,w,_,a,r,e,_,y,o,u }
for (int i = 0; i<dimension; i++)
{
cout<<vect[dimension];
Sleep(delay_time);
}
This is the only solution i have found. 这是我发现的唯一解决方案。 It works but, it is very uncomfortable to use.
它可以工作,但是使用起来非常不舒服。
Does anyone have a better idea? 有谁有更好的主意吗? I hope the community can help me :)
我希望社区能够帮助我:)
Thanks for your time. 谢谢你的时间。
You can actually index the individual characters of a std::string
. 实际上,您可以索引
std::string
的各个字符。 Your function could look like this: 您的函数可能如下所示:
void slow_print(const std::string& str, int delay_time) {
for (size_t i = 0; i != str.size(); ++i) {
std::cout << str[i];
Sleep(delay_time);
}
}
You can use something like that: 您可以使用类似这样的内容:
unsigned long k;
std::string str="Hello"
for (k=0;k<str.size();++k) {
std::cout << str[k]; Sleep(5);
}
You are able to index a string. 您可以索引一个字符串。 If
str
is equal to "Hello"
, str[0]
, for example, will be equal to 'H'
. 如果
str
等于"Hello"
,则str[0]
等于'H'
。
If you use c++11 or later... 如果您使用c ++ 11或更高版本...
std::string str("hello.");
std::for_each(str.begin(), str.end(), [](char c){
std::cout << c;
Sleep(1000);
});
std::for_each
comes from <algorithm>. std::for_each
来自<算法>。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.