2016-12-05 326 views
-2

我使用stringstream来解析字符串,但是它在从函数中退出时出乎意料地给出了段错误。从C++中的函数返回时出现分段错误

bool check_if_condition(int a) 
{ 
    string polygonString1="19.922379 51.666267 19.922381 51.665595 19.921547 51.665705 19.921218 51.665753 19.920787 51.665815 19.919753 51.665960 19.919952 51.666897 19.920395 51.666826 19.920532 51.667150 19.920830 51.667748 19.920989 51.667905 19.921690 51.667906 19.922141 51.662866 19.922855 51.668696 19.922664 51.668237 19.922610 51.668025 19.922464 51.667451 19.922355 51.666732 19.922379 51.666267"; 

    double buf1; // Have a buffer string 
    stringstream ssPolygonString1(polygonString1); // Insert the string into a stream 

    double polygon1[2]; // Create vector to hold our words 
    int iterPoly1=0; 
    while (ssPolygonString1 >> buf1) 
    { 
     polygon1[iterPoly1]=(buf1);  
     cout<<"buf1="<<buf1<<"\n"; 
     iterPoly1++; 
    } 
    ssPolygonString1.str(""); 
    cout<<"Return true"; 
    return true; 
} 

main() 
{ 
    check_if_condition(1); 
} 

有人可以帮我理解函数调用有什么问题吗?

我使用C++ 11

我跑它https://www.tutorialspoint.com/compile_cpp11_online.php,它给我总线错误(核心转储)

+0

编译所有警告和调试信息('g ++ -Wall -g')。使用调试器('gdb') –

+0

@BasileStarynkevitch我跑它https://www.tutorialspoint.com/compile_cpp11_online.php,它给我总线错误(核心转储) –

+2

'双polygon1 [2];'为什么2 ? – kennytm

回答

5

我认为,当你说double polygon1[2]您想您的评论来创建矢量。

如果您使用矢量,您的代码将工作。

另外,当你使用一个矢量,确保你使用vector.push_back();

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

using namespace std; 
bool check_if_condition(int a) 
{ 
    string polygonString1 = "19.922379 51.666267 19.922381 51.665595 19.921547 51.665705 19.921218 51.665753 19.920787 51.665815 19.919753 51.665960 19.919952 51.666897 19.920395 51.666826 19.920532 51.667150 19.920830 51.667748 19.920989 51.667905 19.921690 51.667906 19.922141 51.662866 19.922855 51.668696 19.922664 51.668237 19.922610 51.668025 19.922464 51.667451 19.922355 51.666732 19.922379 51.666267"; 

    double buf1; // Have a buffer string 
    stringstream ssPolygonString1(polygonString1); // Insert the string into a stream 
    vector<double> polygon1; // Create vector to hold our words 
    int iterPoly1 = 0; 
    while (ssPolygonString1 >> buf1) 
    { 
     //polygon1[iterPoly1] = (buf1); 
     polygon1.push_back(buf1); // Add buf1 to vector. 
     cout << "buf1=" << buf1 << "\n"; 
     iterPoly1++; 
    } 
    ssPolygonString1.str(""); 

    //Print vector to show it works! 
    for (int i = 0; i < polygon1.size(); i++) 
    { 
     cout << polygon1.at(i) << endl; 
    } 
    cout << "Return true"; 
    return true; 
} 

int main() 
{ 
    check_if_condition(1); 

    system("pause"); 

    return 0; 
} 
0

的错误是在该行: polygon1 [iterPoly1] =(BUF1);

因为矢量的长度是2和iterPoly即将上述2.所以行为是出乎意料的。