2012-10-13 99 views
2

我想有這將運行兩個函數的main()創建兩個線程詞之間交替:使用線程開始以元音或長輔音

  • 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(); 
     } 
    } 


} 
+3

'臨時[0] == 'A' || '一' || 'E' || 'E' ||」我'''我''''''''''''''''''有問題。你必須寫temp [0] =='A'|| temp [0] =='a'|| temp [0] =='E'|| ... – andre

+1

哇,最糟糕的使用,線程_ever!_ :-)爲什麼不能反映現實多一點?當然不是OP的錯,但是設置這個任務的人應該塗柏油羽毛,然後跑出城外。 – paxdiablo

回答

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) { 
    ... 
} 
+1

這樣做。感謝您指出了這一點。 – user1743959

相關問題