为什么我从g ++中得到这个错误信息? [英] Why am I having this error message from g++?

查看:151
本文介绍了为什么我从g ++中得到这个错误信息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是我的代码。它在g ++中编译得很好,但总是有这种运行时错误:分段错误(核心转储)

我错在哪里?

 #include< iostream> 
#include< string>

使用namespace std;
$ b $ void sort_string(string x){
for(int i = 0; x.size(); i ++){
for(int j = i; x.size( ); j ++){
char temp = x [i];
if(temp> x [j]){
x [j] = temp;
x [i] = x [j];






int main(){
字符串单词;
cin>>话;

while(words!=){
cout<<字<< ;
sort_string(words);
cout<<字<< ENDL;
}

}


解决方案

你正在循环超出字符串的范围。您需要:

  for(int i = 0; i< x.size(); i ++){...} 

类似于内部循环。 x.size()将计算为 true ,除非字符串为空。由于这是循环终止条件,所以循环会永久运行非空字符串。


Below is my code. It compiles fine in g++, but there is always this running time error: Segmentation fault (core dumped)

Where am I wrong?

#include<iostream>
#include<string>

using namespace std;

void sort_string(string x){
    for (int i=0;x.size();i++){
                    for(int j=i;x.size();j++){
                            char temp = x[i];
                            if (temp > x[j]){
                                    x[j]=temp;
                                    x[i]=x[j];
                            }
                    }
    }
}


int main(){
    string words;
    cin >> words;

    while (words != " "){
            cout << words << " ";
            sort_string(words);
            cout << words << endl;
    }

}

解决方案

You are looping beyond the bounds of the string. You need this:

for (int i=0; i<x.size(); i++){ ... }

Similarly for the inner loop. x.size() will evaluate to true unless the string is empty. Since this is the loop termination condition, the loops will run forever for non-empty strings.

这篇关于为什么我从g ++中得到这个错误信息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆