LL Golf Hole 1 - tinyurl.comを使ってURLを短縮する
Posted feedbacks - C++
MSXMLのXmlHttpRequestを使いました。というわけでWindows限定です。さらに、#importを使っているので、Visual C++などでしかコンパイルできないです。なお、#import内のmsxml6.dllはmsxml3.dllやmsxml4.dllに置き換えても動くでしょう。
このプログラム自体は、std::wstringを全く使わなくても出来上がりますが、コピペして使い回すときの便を(少しだけ)考えてstd::wstringで入出力するようにしてあります。
XMLHTTPRequestの各メソッド・プロパティも_com_errorを投げる可能性があります。使い回すときには考慮しておいたほうが良いでしょう。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 | #include <iostream>
#include <boost/algorithm/string/predicate.hpp>
#include <boost/range.hpp>
#include <comdef.h>
#include <comutil.h>
#import <msxml6.dll>
_bstr_t ToBStr(const std::wstring& s)
{
return _bstr_t(SysAllocStringLen(s.c_str(), s.size()), false);
}
std::wstring ToWString(const _bstr_t& s)
{
return std::wstring(static_cast<PCWSTR>(s), static_cast<PCWSTR>(s) + s.length());
}
boost::iterator_range<const wchar_t*> BStrRange(const _bstr_t& s)
{
return boost::make_iterator_range(static_cast<PCWSTR>(s), static_cast<PCWSTR>(s) + s.length());
}
std::wstring GetTinyUrlString(const std::wstring& url)
{
MSXML2::IXMLHTTPRequestPtr xmlhttp;
HRESULT hr = xmlhttp.CreateInstance("Msxml2.XMLHTTP");
if (FAILED(hr))
{
throw _com_error(hr);
}
xmlhttp->open(L"GET", ToBStr(L"http://tinyurl.com/api-create.php?url=" + url));
xmlhttp->send();
_bstr_t result = xmlhttp->GetresponseText();
if (boost::algorithm::iequals(BStrRange(result), L"error"))
{
throw std::runtime_error("Tinyurl returns error");
}
return ToWString(result);
}
int main()
{
HRESULT hr = CoInitialize(0);
if (FAILED(hr))
{
throw _com_error(hr);
}
std::wcout << GetTinyUrlString(L"http://ll.jus.or.jp/2008/info/xgihyo") << std::endl;
CoUninitialize();
}
|


takano32
#6771()
[
Ruby
]
Rating-4/16=-0.25
tinyurl.com( http://tinyurl.com/ )のサービスを利用し、 http://ll.jus.or.jp/2008/info/xgihyo というURLを短縮しなさい。tinyurl.comのalias機能は使わないものとする。 なお、参考までに短縮したURLは http://tinyurl.com/5mngx8 となる。
余力のあるものはこのプログラムを短くしてみたり、短くしてみたり、短くしてみよ。
※LL Future実行委員の高野光弘です。この出題は LL Future公式の出題であり、優れたものについてはLL Golfのセッションでご紹介させていただくかもしれません。ご理解の上、ご投稿ください。また、LL Futureのチケットは現在も発売中です。よろしければ、メインイベントの方にもぜひご参加ください。
see: tinyurl.comでURLを短縮するRubyスクリプト
Rating-4/16=-0.25-0+
[ reply ]