I am writing a C ++ program. It is required that the string be output with pauses, i.e. letter, delay, letter, delay, etc. Tell me how to write it, please.
3 answers
For example:
void outDelay(const std::string& s, int ms) { for(auto c: s) { std::cout << c; std::this_thread::sleep_for(std::chrono::milliseconds(ms)); } } int main(int argc, const char * argv[]) { outDelay("Hello",500); } - Swears on this_thread: error: | 'std :: this_thread' has not been declared | - Mark Bale
- Add #include <thread> and #include <chrono> - Harry
- 2This is C ++ 11, if the compiler is older - use the operating system API. - Harry
- And can you somehow get by with C ++ 03? - Mikhailo
- @Mikhailo Well ... Frankly, if you don鈥檛 use APO, then, except polling
clock()in a cycle, until the right time has passed, I don鈥檛 see any options. - Harry
|
There are many ways, you can delay the flow, but you can not, for example:
#include <iostream> #include <string> #include <chrono> using namespace std::chrono; void timedCout(const std::string& str, double ms) { high_resolution_clock::time_point t1 = high_resolution_clock::now(); int i = 0; std::cout << str[i++]; while (i < str.size()) { high_resolution_clock::time_point now = high_resolution_clock::now(); duration<double> time_span = duration_cast<duration<double>>(now - t1); if (time_span.count() >= ms) { t1 = now; std::cout << str[i++]; } } } int main(int argc, char *argv[]) { std::string str = "timedcout"; timedCout(str, 0.6f); return 0; } - Do not thresh the cycle idle! - 伪位蔚蠂慰位蠀蟿
- @alexolut really, and how many idle iterations do you have here? - ampawd
- add a counter to the while, but count - 伪位蔚蠂慰位蠀蟿
|
The unistd.h library has a usleep() function.
#include <unistd.h> #include <iostream> int main() { for (int i = 0; i < 10; i++) { std::cout << "String\n"; // 锌邪褍蟹邪 1 褋械泻褍薪写邪 usleep (1000000); } } |
sleepfunction. - 伪位蔚蠂慰位蠀蟿