简体   繁体   English

c ++ stringstream转换错误:分段错误

[英]c++ stringstream conversion error: segmentation fault

I am having some trouble with a simple function that tries to convert integers to a string. 我在尝试将整数转换为字符串的简单函数时遇到了麻烦。 Here is the code: 这是代码:

string Problem::indexB(int i, int j, int k){    
    stringstream ss;

    if(i < 10)
        ss << "00";
    else if(i<100)
        ss << "0";
    ss << i;

    if(j < 10)
        ss << "00";
    else if(j<100)
        ss << "0";
    ss << j;

    if(k < 10)
        ss << "00";
    else if(k<100)
        ss << "0";
    ss << k;

    return ss.str();
}

The function works fine, but when a make multiple calls it gives me a segmentation fault in some point. 该函数运行良好,但是当进行多次调用时,它在某些时候给了我一个分段错误。

It works fine for me: http://ideone.com/lNOfFZ 对我来说效果很好: http//ideone.com/lNOfFZ

Complete working program: 完整的工作程序:

#include <string>
#include <sstream>
#include <iostream>

using std::string;
using std::stringstream;

class Problem {
public:
    static string indexB(int i, int j, int k);
};

string Problem::indexB(int i, int j, int k){

    stringstream ss;

    if(i < 10)
        ss << "00";
    else if(i<100)
        ss << "0";
    ss << i;

    if(j < 10)
        ss << "00";
    else if(j<100)
        ss << "0";
    ss << j;

    if(k < 10)
        ss << "00";
    else if(k<100)
        ss << "0";
    ss << k;

    return ss.str();
}

int main() {
    std::cout << Problem::indexB(1, 2, 3) << "\n";
    std::cout << Problem::indexB(400, 50, 6) << "\n";
    std::cout << Problem::indexB(987, 65, 432) << std::endl;
}

Segmentation faults often happen a while after the program has run into something with Undefined Behavior, so the stack trace when the error was detected is not necessarily in the same function as the buggy code. 分段错误通常是在程序遇到具有“未定义行为”的错误之后发生的,因此检测到错误时的堆栈跟踪不一定与错误代码具有相同的功能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM