2012-02-09 56 views
0

對不起noob問題找不到在這裏使用哪些函數。 http://www.cplusplus.com/reference/string/string/將string.h分段錯誤排入隊列

是否會轉換爲C字符串並編寫一大堆代碼,但我敢打賭有一個很好的方法來做到這一點。

試圖將A,B和C附加到一個字符串的末尾並將其添加到隊列中,然後繼續在string :: assign()之後得到一個?()函數終止的分段錯誤tho(根據調試器)

string a, b, c; 
a = s.append("A"); 
b = s.append("B"); 
c = s.append("C"); 

q.add(a); 
q.add(b); 
q.add(c); 

這也結束了分段錯誤。

q.add(s + "A"); 
q.add(s + "B"); 
q.add(s + "C"); 

而且這個問題是使用舊的,所以我會得到:

teststringA 
teststringAB 
teststringABC 

,而不是預期的

teststringA 
teststringB 
teststringC 
+3

請發佈一個[*完整*示例來演示您的問題](http://sscce.org/)。您發佈的代碼應該沒有問題。 – 2012-02-09 06:33:54

+2

我沒有看到的唯一的東西是s的定義。你能告訴我們嗎? – 2012-02-09 06:43:00

+0

如果您使用的是標準庫'std :: string',則應該包含'',而不是''。它看起來不像你使用'std :: queue',所以你應該發佈你的隊列代碼。 – Blastfurnace 2012-02-09 08:10:22

回答

0

What is a segmentation fault?

當程序運行時,它可以訪問某些內存部分。首先,你在每個函數中都有局部變量;這些都存儲在堆棧中。其次,你可能有一些內存,在運行時分配(使用malloc,C或新的C++),存儲在堆上(你也可能會聽到它叫做「free store」)。您的程序只允許觸摸屬於它的內存 - 前面提到的內存。在該區域之外的任何訪問都將導致分段錯誤。分段錯誤通常被稱爲分段錯誤。

你的第二個問題是

q.add(s + "A"); // appends A to s hence teststringA 
q.add(s + "B"); // teststringA + B hence teststringAB 
q.add(s + "C"); //teststringAB + C hence teststringABC 

http://www.cplusplus.com/reference/string/string/append/

Append to string 
The current string content is extended by adding an additional appending string at its end. 

The arguments passed to the function determine this appending string: 

string& append (const string& str); 
    Appends a copy of str. 

例如參考文獻

// appending to string 
#include <iostream> 
#include <string> 
using namespace std; 

int main() 
{ 
    string str; 
    string str2="Writing "; 
    string str3="print 10 and then 5 more"; 

    // used in the same order as described above: 
    str.append(str2);      // "Writing " 
    str.append(str3,6,3);     // "10 " 
    str.append("dots are cool",5);   // "dots " 
    str.append("here: ");     // "here: " 
    str.append(10,'.');      // ".........." 
    str.append(str3.begin()+8,str3.end()); // " and then 5 more" 
    str.append<int>(5,0x2E);    // "....." 

    cout << str << endl; 
    return 0; 
} 

輸出:

Writing 10 dots here: .......... and then 5 more.....