LoginSignup
3
2

More than 3 years have passed since last update.

【C++】GoogleChromeで指定のURLを開く方法

Posted at

目的

AtCoderの過去問をランダムに開いて勉強できるようにしたい.

方法

1. C++を用いて指定のアプリケーションを開く

「C++ URL 開き方」などで検索をすると,ShellExecute関数というものがヒットした.
使い方をいくらか調べたが,Macでの使い方がうまくヒットしなかったため断念した.

ShellExcute.cpp
ShellExecute( hWnd, "open", "http://www.google.co.jp/", NULL, NULL, SW_SHOWNORMAL );

どうやらここによると

WindowsだとShellAPI.ShellExecuteを使えばいいんだけど、WindowsAPIなのでこれはMacOSXでは使えない。

らしい.そろそろAPIが何なのかしっかり理解する必要がありそう.

次に関連事項を検索しているとC++で別のプログラムを開く方法がヒットした.

System.cpp
int system( const char* command );

コマンドを書けばそれを実行してくれる関数だった.

2. 指定のURLを開く方法

コマンドを実行するための関数が見つかったため,あとはコマンドでURLを開く方法を検索すれば良いことがわかった.

どうやら
open -a '/Applications/Google Chrome.app' <URL>
を実行すれば指定のURLを開けるようだ.

よって以下のように作成した.

RandomAtCoder.cpp
#include<iostream>
#include<string>

using namespace std;

// ランダム関数
int RandomNum(){
    return rand()%146+1;
}

int main(){
    srand((unsigned int)time(NULL));
    int problemNum = RandomNum();
    string com = "open -a '/Applications/Google Chrome.app' https://atcoder.jp/contests/abc";

    // 桁が違う場合文字数を合わせるURLだったためif文で分岐している(1→001や15→015など)
    if(problemNum<10){
        com = com + "00" + to_string(problemNum) + "/tasks";  
    }
    else if(problemNum<100){
        com = com + "0" + to_string(problemNum) + "/tasks";
    }
    else{
        com = com + to_string(problemNum) + "/tasks";      
    }
    // コンソールにコマンドを書き込む際,char型である必要があるのでstringから変換
    system(com.c_str());
    return 0;
}

結論

本当は難易度の入力をさせてその難易度の問題をランダムに開くようにしたかったのだが,URLが定性的ではなかったので断念.
ABC問題どARC問題選べるプログラムも書いてみる.

3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2