2012-02-09 74 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.....