PDA

View Full Version : سوال: صبر کردن برای دریافت ورودی ممکنه؟



aliv.2022
یک شنبه 09 آذر 1393, 20:15 عصر
یه سوال دارم ولی نمیدونم ممکنه یا نه!
میشه یه جوری گفت که برنامه مثلا 5ثانیه صبر کنه تا کاربر یه ورودی وارد کنه، و اگه چیزی وارد نکرد یکاری کنه؟

omid_kma
یک شنبه 09 آذر 1393, 21:42 عصر
میشه یک thread جدا ساخت و داخل اون چک کرد چیزی وارد شده یا نه .
مثلا

#include <iostream>
#include <string>
#include <thread>
#include <chrono>
#include <conio.h>


class Input
{
public:
std::string getString(std::chrono::seconds sec)
{
str.clear();
std::thread th([&sec,this](){
while (str.empty())
{
//age chizi vared nashode bashe in ghesmat ejra mishe
std::cout << "Please enter something... \n";
std::this_thread::sleep_for(sec);
}
});
int ch = getch();
while (ch != 13)
{
std::cout << (char)ch;
str.push_back((char)(ch));
ch = getch();
}
th.join();
return str;
}


private:
std::string str;
};
int main()
{
Input input;
auto str=input.getString(std::chrono::seconds(1));
std::cout << "\nstring is : " << str;
return 0;
}

iut.ali
دوشنبه 10 آذر 1393, 22:16 عصر
نیازی به thread نیس با کتابخونه ی chrono میتونی اینکارو انجام بدی

omid_kma
دوشنبه 10 آذر 1393, 23:16 عصر
نیازی به thread نیس با کتابخونه ی chrono میتونی اینکارو انجام بدی
! Talk is cheap. Show me the code (http://izquotes.com/quote/273528)

rahnema1
سه شنبه 11 آذر 1393, 11:02 صبح
سلام
میشه از wait هم استفاده کرد. با ترکیب کد آقای omid_kma و همچنین لینک زیر یه همچین چیزی میشه
http://www.cplusplus.com/reference/condition_variable/condition_variable/wait_for

#include <iostream>
#include <string>
#include <thread>
#include <chrono>
#include <conio.h>
#include <mutex>
#include <condition_variable>

class Input
{
public:
std::string getString(std::chrono::seconds sec)
{
char _ch;
std::condition_variable cv;
std::mutex mtx;
std::unique_lock<std::mutex> lck(mtx);
str.clear();
std::thread th([&_ch, &cv, this]()
{
std::cout << "Please enter something... \n";
if((_ch = getch()) != 13)
cv.notify_one();
});
if (cv.wait_for(lck, std::chrono::seconds(sec)) == std::cv_status::timeout)
{
std::cout << "timeout elapsed!";
th.detach();
return str;
}
do
{
std::cout << _ch;
str.push_back(_ch);
_ch = getch();
}
while (_ch != 13);
th.join();
return str;
}
private:
std::string str;
};
int main()
{
Input input;
auto str=input.getString(std::chrono::seconds(5));
if (str.empty())
std::cout << "\ndo something...";
else
std::cout << "\nstring is : " << str;
return 0;
}

aliv.2022
سه شنبه 11 آذر 1393, 11:28 صبح
نیازی به thread نیس با کتابخونه ی chrono میتونی اینکارو انجام بدی

فکر نمیکنم بشه این که شما میگی، با اون 2تا کار همزمان نمیشه انجام داد!

iut.ali
سه شنبه 11 آذر 1393, 13:09 عصر
! Talk is cheap. Show me the code (http://izquotes.com/quote/273528)
حق با شماس من سوالو درست متوجه نشده بودم متاسفم ...