2013-02-19 68 views
0

我遇到了一些简单的函数,试图将整数转换为字符串的麻烦。下面是代码:C++ stringstream转换错误

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(); 
} 

功能工作正常,但是当多次调用它给了我一些点分段错误。

+0

哪一点?你做了什么来调试它? – StoryTeller 2013-02-19 15:49:55

+3

错误不在此代码片段中。尝试使用valgrind来定位堆栈损坏或类似 – 2013-02-19 15:49:57

+0

问题出在返回行。我多次调用函数“.str()”后会导致分段错误。这是gdb的相关问题 '程序接收到的信号SIGSEGV,分段错误。 _int_malloc(av = 0x7ffff74191c0,bytes = 26)at malloc.c:4339 malloc.c:找不到文件或目录。 \t in malloc.c' – user569709 2013-02-19 17:35:41

回答

1

它正常工作对我来说:http://ideone.com/lNOfFZ

完整的工作方案:该方案已运行到的东西与未定义行为后

#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; 
} 

分段错误经常发生一段时间,所以堆栈跟踪时出错被发现并不一定与多功能代码具有相同的功能。

+0

与gdb相关的问题在“.str()”函数中。这里是我从调试器得到的信息'程序接收到的信号SIGSEGV,分段错误。 malloc.c中的_int_malloc(av = 0x7ffff74191c0,bytes = 26):4339 4339 malloc.c:未找到文件或目录。 in malloc.c' – user569709 2013-02-19 17:37:36

+0

找到了!问题在于我将结果存储在向量中。经过一些电话后,我清除了矢量,而不是再次调整大小。问题不在于返回,而在于用于存储结果的变量。谢谢。 – user569709 2013-02-19 17:52:46