重要なお知らせ

「教えて! goo」は2025年9月17日(水)をもちまして、サービスを終了いたします。詳細はこちら>

電子書籍の厳選無料作品が豊富!

アルゴリズムを勉強するときに以下のソースを書きました;

void weighted_quick_union_algorithm() {
static const int volume = 10;

enum status {
terminate_,
union_,
find_
};
string str;
status sta;
vector<int> system(volume, 0);
vector<int> size(volume, 1);
for (int index = 0; index != volume; ++index) {
system[index] = index;
}

do {
cout<<"cin"<<endl;
cin >> str;
for (string::size_type index = 0; index != str.size(); ++index) str[index] = toupper(str[index]);

if (str == "UNION") sta = union_;
else if (str == "FIND") sta = find_;
else if (str == "TERMINATE") sta = terminate_;

switch (sta) {
case(0):
{
cout << str << endl;
break;
}
case(1):
{
cout << str << sta << endl;
int p(0), q(0), i(0), j(0);
while (cin >> p) {
cin >> q;
for (i = p; i != system[i]; i = system[i]);
for (j = q; j != system[j]; j = system[j]);
if (i == j) continue;
if (size[i] < size[j]) {
system[i] = j;
size[j] += size[i];
} else {
system[j] = i;
size[i] += size[j];
}
cout << p << " - " << q << endl;
}
cout<<"break"<<endl;
break;
}
case(2):
{
cout << str << sta << endl;
break;
}
}
} while (sta);
}

しかし unionを入力しあと ; でwhile(cin>>p)をブレイクしたら
cin
break
UNION1
cin
break
Union1
で無限ループ

結構時間かかったが間違いがわかりません
ちなみに最少は while(cin>>p>>q)と書いていましたが同じ結果です。
どうかお願いします

A 回答 (1件)

>cout<<"break"<<endl;


ここらへんに
cin.clear();
を入れたら解決しませんか。
勘違いだったら申し訳ないですが、while(cin>>p)を抜けるときにeofフラグが立ってそれ以降のcinがスルーされてるんじゃないかと。
    • good
    • 0
この回答へのお礼

解決しました、素早いお返事ありがとうございました、助かりました!

お礼日時:2014/02/16 03:22

お探しのQ&Aが見つからない時は、教えて!gooで質問しましょう!