我不確定您的問題是關於如何將整數轉換爲字符串,還是關於將圖像顯示15秒。但是,下面的代碼應該向您展示兩種方法。
最主要的是主循環等待事件的時間長達100ms,如果你這樣做了150次,你的屏幕會顯示大約15秒。
#include <iostream>
#include "CImg.h"
using namespace std;
using namespace cimg_library;
#define BUFSIZE 128
int main(int argc, char** const argv)
{
// Create empty yellow image
CImg<unsigned char> image(256,256,1,3);
cimg_forXY(image,x,y) { image(x,y,0,0)=255; image(x,y,0,1)=255; image(x,y,0,2)=0; }
unsigned char red[] = { 255,0,0 };
unsigned char blue[] = { 0,0,255 };
char text[BUFSIZE];
int someInt=42;
snprintf(text,BUFSIZE,"Hello, the integer is %d",someInt);
image.draw_text(5,5,text,red,blue,1,10);
CImgDisplay main_disp(image,"Hello world");
// Loop 150 times @100ms each
for(int i=0;i<150;i++){
if(main_disp.is_closed()){break;}
main_disp.wait(100);
}
}
還有其他更多的C++,得到一個整數轉換成字符串的方法,但這種方法將讓你開始。
運行15秒的方法也相當粗糙,但我懷疑它只是一個標稱的15秒你想要的。您可以在程序開始時使用time()
獲得時間,然後在循環中每次通過時再次獲取時間,並在差值超過15時中斷時間 - 但這比上面的簡單方法稍微清晰一些。該代碼看起來是這樣的:
#include <iostream>
#include <ctime>
#include "CImg.h"
using namespace std;
using namespace cimg_library;
#define BUFSIZE 128
int main(int argc, char** const argv)
{
// Create empty yellow image
CImg<unsigned char> image(256,256,1,3);
cimg_forXY(image,x,y) { image(x,y,0,0)=255; image(x,y,0,1)=255; image(x,y,0,2)=0; }
unsigned char red[] = { 255,0,0 };
unsigned char blue[] = { 0,0,255 };
char text[BUFSIZE];
int someInt=42;
snprintf(text,BUFSIZE,"Hello, the integer is %d",someInt);
image.draw_text(5,5,text,red,blue,1,10);
CImgDisplay main_disp(image,"Hello world");
time_t start,diff;
start=time(NULL);
// Loop till display closed or 15 seconds elapsed
while(1){
// Exit if closed
if(main_disp.is_closed()){break;}
// Exit if 15 seconds are up
diff=time(NULL)-start;
if(diff>15){break;}
main_disp.wait(10);
}
}
你可以做字符串的東西,在這樣的多C++方式:
#include <iostream>
#include <sstream>
#include <ctime>
#include <string>
#include "CImg.h"
using namespace std;
using namespace cimg_library;
int main(int argc, char** const argv)
{
// Create empty yellow image
CImg<unsigned char> image(256,256,1,3);
cimg_forXY(image,x,y) { image(x,y,0,0)=255; image(x,y,0,1)=255; image(x,y,0,2)=0; }
unsigned char red[] = { 255,0,0 };
unsigned char blue[] = { 0,0,255 };
int someInt=42;
string text="The integer is: ";
text += to_string(someInt);
image.draw_text(5,5,text.c_str(),red,blue,1,10);
CImgDisplay main_disp(image,"Hello world");
time_t start,diff;
start=time(NULL);
// Loop till display closed or 15 seconds elapsed
while(1){
// Exit if closed
if(main_disp.is_closed()){break;}
// Exit if 15 seconds are up
diff=time(NULL)-start;
if(diff>15){break;}
main_disp.wait(10);
}
}