【问题标题】:Can't get toupper to work with a vector无法让 toupper 使用矢量
【发布时间】:2013-08-19 01:01:04
【问题描述】:

我正在做一个练习,将单词存储在strings 的<vector> 中,然后将所有字母转换为大写,每行打印出八个单词。除了我的代码的toupper() 部分外,一切正常。一切都在这里:

vector<string> words;
string theWords;
string word;

while(cin >> word)
    words.push_back(word);

for(auto &i : words) {
    word = i;
    for(auto &j: word)
        j = toupper(j);
}

int k = 0;
for(auto i : words) {
    cout << i << " ";
    ++k;
    if(k % 8 == 0)
        cout << endl;
}

【问题讨论】:

  • 欢迎来到 Stack Overflow。为了最好地回答问题,您应该始终尝试发布sscce,说明您期望的输出/行为以及您看到的输出/行为。如果您遇到编译错误,请发布编译器错误。 stackoverflow.com/questions/how-to-ask
  • 我以前没遇到过。我以后会这样做的,谢谢。

标签: c++ vector toupper


【解决方案1】:

您将新更新的字符串存储在word,但您应该更新i

改变这个

for(auto &i : words) {
    word = i;
    for(auto &j: word)    // word is updated, but your vector is not
        j = toupper(j);
}

...到这个:

for (auto &i : words)      // for every string i in words vector
    for (auto &j : i)      // update your i, not word
        j = toupper(j);

【讨论】:

    【解决方案2】:

    您正在将临时字符串“word”转换为大写,然后将其丢弃。

    string word;
    
    for(auto &i : words) {
        word = i; <<-- here
        for(auto &j: word)
            j = toupper(j);
    }
    

    你需要做的是

    for(auto &i : words) {
        for(auto &j: i)
            j = toupper(j);
    }
    

    现场演示:http://ideone.com/pwQBQr#

    【讨论】:

      【解决方案3】:

      聚会有点晚了,但这里有一个没有额外循环的版本。

      for(auto &i : words)
          std::transform(i.begin(), i.end(), i.begin(), ::toupper);
      

      【讨论】:

        【解决方案4】:

        表达式word = i 使用了字符串复制构造函数。 word 不是向量中的那个。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2021-12-10
          • 2020-06-23
          • 2018-07-24
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多