2

main()2 つの関数を実行する 2 つのスレッドを作成 しようとしています。

  • vow- 母音で始まる単語を出力します
  • cons- 子音で始まる単語を出力します。

これらの単語はテキスト ファイルから取得され、ベクトルに読み込まれます。現在のコードは単語を正しい順序で出力しますが、すべての単語を母音で始まる単語としてラベル付けしています。テスト文を使用しています:"Operating Systems class at college."

現在、すべての母音をチェックしている if ステートメントを O (大文字の o) のみをチェックするように変更した場合、「Operating」は正しい母音としてラベル付けされ、残りは子音としてラベル付けされます。何がうまくいかないのですか?

同期技術の使用は許可されていません。

#include <iostream>
#include <thread>
#include <fstream>
#include <string>
#include <iterator>
#include <vector>
#include <sstream>

using namespace std;

int cons(string temp){
    cout << "cons:  " << temp << endl;
    //this_thread::yield();
    return 0;
}

int vow(string temp){
    cout << "vow:   " << temp << endl;
    //this_thread::yield();
    return 0;
}


int main(){
    string sentence, temp;
    ifstream ifs;
    ofstream ofs;
    vector <thread> wordThreads;

    ifs.open("phrase.txt");
    getline(ifs, sentence);
    istringstream s(sentence);
    istream_iterator<string> begin(s), end;
    vector<string> words(begin, end); 

    ifs.close();

    for(int i=0; i<(int)words.size(); i++) {
        temp = words[i];
        if(temp[0] == 'A'||'a'||'E'||'e'||'I'||'i'||'O'||'o'||'U'||'u') {
            thread threadOne(vow, temp);
            threadOne.join();
        }
        else {
            thread threadTwo(cons, temp);
            threadTwo.join();
        }
    }


}
4

1 に答える 1

2

temp[0] == 'A'||'a'||'E'||'e'||'I'||'i'||'O'||'o'||'U'||'u'あなたが思っていることを評価しません。その結果、常にブランチが取得されます。temp[0] == 'A'最初に評価されます。false の場合、後続の各文字リテラル式が評価され、分岐の条件として扱われます。'A''a'などはすべて非ゼロであるため、分岐は常に行われます。もしかして、こういう意味だったの?

temp[0] == 'A' || temp[0] == 'a' || temp[0] == 'E' || ...

...またはおそらく次のようなもの:

std::string vowels = "AaEeIiOoUu";
...
if (vowels.find(temp[0]) > 0) {
  ...
}
于 2012-10-13T21:39:39.407 に答える