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


}
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 回答