C++ Can';Don’不要让toupper使用向量
我正在做一个练习,将单词存储在C++ Can';Don’不要让toupper使用向量,c++,vector,toupper,C++,Vector,Toupper,我正在做一个练习,将单词存储在字符串的中,然后将所有字母转换为大写,每行打印8个单词。除了我的代码中的toupper()部分之外,一切都正常。这里是: vector<string> words; string theWords; string word; while(cin >> word) words.push_back(word); for(auto &i : words) { word = i; for(auto &j:
字符串的
中,然后将所有字母转换为大写,每行打印8个单词。除了我的代码中的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;
}
向量词;
把单词串起来;
字符串字;
while(cin>>word)
单词。推回(单词);
用于(自动和输入:文字){
word=i;
用于(自动和j:word)
j=toupper(j);
}
int k=0;
for(自动i:words){
cout您正在将新更新的字符串存储在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);
您正在将临时字符串“word”转换为大写,然后丢弃它
string word;
for(auto &i : words) {
word = i; <<-- here
for(auto &j: word)
j = toupper(j);
}
这里的实时演示:表达式word=i
使用了字符串复制构造函数。word
不是矢量中的一个。有点晚了,但这里有一个没有额外循环的版本
for(auto &i : words)
std::transform(i.begin(), i.end(), i.begin(), ::toupper);
欢迎使用Stack Overflow。为了获得对问题的最佳回答,您应该始终尝试发布一个,您期望的输出/行为是什么,以及您看到的输出/行为是什么。如果您有编译错误,请发布编译器错误。我以前没有遇到过taht。我将来会这样做,谢谢。
for(auto &i : words)
std::transform(i.begin(), i.end(), i.begin(), ::toupper);