【问题标题】:Why does break statement terminate program?为什么break语句会终止程序?
【发布时间】: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


【解决方案1】:

你写过

sort(indices_sorted.end(),indices_sorted.begin());

这违反了std::sort 的前提条件,即第二个迭代器必须可以通过递增从第一个迭代器到达。除非indices_sorted 为空(即begin 等于end),否则您的代码中不会出现这种情况,因此您正在调用未定义的行为。

你需要交换参数

sort(indices_sorted.begin(),indices_sorted.end());

然后是你的程序works

【讨论】:

  • 有效......但只有(似乎)有两个输入词。尝试输入alan kate bob dave break。
  • @AdrianMole 嗯,好点。我不确定最后一部分应该做什么,所以我会尝试澄清一下。
  • 嘿,最后一部分应该按从最短到最长的顺序排列单词。该算法现在正在转换为整数的长度,将其保存在两个向量上并对其中一个进行排序。然后最后一个循环比较排序和未排序,如果两者的长度相同,则将位置 word[counter] 传递给 words_sorted。在当前代码中,现在存在一个错误,即已经使用的索引仍然可以使用。我通过将 unsorted_lengths[counter] 设置为零来解决这个问题。对于简单的任务,可能需要进行大量计算,但我希望这能说明问题!
猜你喜欢
  • 1970-01-01
  • 2011-02-28
  • 2021-10-30
  • 2014-01-08
  • 1970-01-01
  • 1970-01-01
  • 2021-05-20
  • 2017-07-03
  • 2022-01-11
相关资源
最近更新 更多