【发布时间】:2021-04-28 15:31:37
【问题描述】:
我有一个 break 语句来退出循环:
while (cin >> text){
if (text == "break"){
break;
};
cout << text << endl;
words.push_back(text);
}
问题是程序随后就停止了
退出代码:0(正常程序终止)。
这是我的完整程序:
// Example program
#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
using namespace std;
int main()
{
string text;
vector<string> words;
vector<int> indices;
vector<int> indices_sorted;
vector<string> words_sorted;
cout << "type in you're desired Text: ";
while (cin >> text){
if (text == "break"){
break;
};
cout << text << endl;
words.push_back(text);
}
int size = words.size();
for (int i =0; i < size; i++){
indices_sorted.push_back(words[i].size());
}
indices = indices_sorted;
sort(indices_sorted.end(),indices_sorted.begin());
cout << "you typed: " << words.size() << " words!";
int counter = 0 ;
for (int i =0; i < size; i++){
while (indices[i] != indices[counter])counter++;
words_sorted.push_back(words[counter]);
counter = 0;
cout << words_sorted[i]<< endl;
}
return 0;
}
【问题讨论】:
-
这可能与您的环境有关。你在使用 IDE 吗?它是 Windows 上的 Visual Studio 社区吗?如果是这样,您可能只需要在程序退出之前
std::cin.get();以保持窗口打开。 -
嘿,我现在只是在使用这个网站cpp.sh。
-
我写了一个答案,通过删除 UB 来“修复”该错误,但最后的嵌套循环可能也没有做你想要的。您能否添加该代码假定要做什么的描述?
-
@cigien 我应该添加到代码中吗?或者在cmets上解释一下?我修复了剩余的代码!感谢您提供非常有用的修复。我以为我可以从高到低排序。
-
由于该错误不依赖于
sort之后的内容,因此只需修复该部分代码(并在问题中进行,而不是在 cmets 中进行)。顺便说一句,你绝对可以从高到低排序,但你会写sort(indices_sorted.begin(),indices_sorted.end(), std::greater{});。
标签: c++ while-loop break