cin編
ここでは,キーボードからの入力方法の詳細を説明する.
C++のストリームにおいて,キーボードから1文字入力し,変数に代入するには,cin.get() を使用する.
#include <iostream>
using namespace std;
int main()
{
char c;
cout << "Input words:";
c = cin.get();
cout << c << endl;
return 0;
}
実行例: Input char:a a Input words:abc a
複数文字を入力しても,最初の1文字だけが返される.
C++のストリームにおいて,キーボードから1行入力し,文字列stringに代入するには,cinと入力ストリーム >> を使用する.
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s;
cout << "Input words:" << endl;
cin >> s;
cout << s.size() << ":" << s << endl;
return 0;
}
実行例: Input words: abcdef 6:abcdef Input words: abc def 3:abc Input words: (問題がある例) aaa bbb ccc 3:aaa
cinのメンバ関数size()関数で,入力された文字数を得られる.
この例のように,入力文字列にスペースやタブなどの区切り文字が入ると,その前の文字までしか代入されない.
(scanf()を使用する際の %s と同じ挙動.)
スペースなどを含め,改行まで一行すべて読み込みたい場合は,getline()を使用する.
#include <iostream>
#include <string>
using namespace std;
int main()
{
cout << "Input words:";
string s;
getline( cin, s );
cout << s.size() << ":" << s << endl;
return 0;
}
実行結果: C:\>test Input words:111 3:111 C:\>test Input words:111 sss aaa 11:111 sss aaa