gpt4 book ai didi

c++ - 获取总线错误 : 10 with string append

转载 作者:太空宇宙 更新时间:2023-11-04 13:54:58 24 4
gpt4 key购买 nike

我有一个函数,它接受两个字符串并确定它们是否相同。我正在尝试标记字符串并将所有标记组合成一个字符串。这是我目前所拥有的,我收到总线错误:10。
任何帮助表示赞赏。

    #include <iostream>
#include <string>
using namespace std;

bool stringCheck(string s1, string s2){
string strCheck1 = "";
string strCheck2 = "";

char *cstr1 = new char[s1.length()]; // char array with length of string
strcpy(cstr1, s1.c_str()); // copies characters of string to char array

char *cstr2 = new char[s2.length()];
strcpy(cstr2, s2.c_str());

char *p1 = strtok(cstr1, " "); // creates a char array that stores token that
// is delimeted
cout << "p1 " << p1 << endl; ///outputs token that is found

strCheck1.append(p1); // appends token to string
cout << "strCheck1 " << strCheck1 << endl; // outputs string

while(p1 != NULL) // while the token is not a null character
{
cout<<"parsing" << endl;
p1 = strtok(NULL, " "); // continue to parse current string.
cout << "p1 " << p1 << endl;
strCheck1.append(p1);
cout << "str1 " << strCheck1 << endl;
}

char * p2 = strtok(cstr2, " ");
cout << "p2 " << p2 << endl;
strCheck2.append(p2);
cout << "strCheck2 " << strCheck2 << endl;

while(p2 != null){
p2 = strtok(NULL, " ");
strCheck2.append(p2);
cout << "str2 " << strCheck2 << endl;
}

if( strCheck1.compare(strCheck2) != 0)
{
return 0;
}
else return 1;
}

int main(void){
string s1 = "jam yoooo jay";
string s2 = "jam yoooo";
if(stringCheck(s1, s2) == 1){
cout << "strings same"<< endl;;
}
else{
cout << "strings not same" << endl;
}

}

是否有条件语句可以配对

while(p1 != NULL)

我知道这是一个非常愚蠢的功能,但只是想提高我的技能。任何帮助表示赞赏!

最佳答案

有些事情你必须改变:

  • char *cstr1 = new char[s1.length()];

    c 字符串以 null 结尾,因此您需要多一个字符来存储空字符:

    char *cstr1 = new char[s1.length() + 1];

    (与 cstr2 相同)

  • strCheck1.append(p1)

    p1不能是空指针(有关详细信息,请参阅 Assign a nullptr to a std::string is safe?)。所以你必须检查...

    if (p1) strCheck1.append(p1);

    (与 p2 相同)。

  • cout << p1 << endl

    如果p1是空指针可能会发生坏事(参见 Why does std::cout output disappear completely after NULL is sent to it )。所以你必须检查...

    if (p1) { cout << "p1 " << p1 << endl; strCheck1.append(p1); }

    (与 p2 相同)

  • 存在内存泄漏(必须删除 cstr1/cstr2)。

最后它应该可以工作。

可能您应该考虑使用其他系统来提取标记(您不必混合使用 std::string 和 c-string)。例如:

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

int main()
{
std::string text("text-to-tokenize");
std::istringstream iss(text);
std::string token;

while(getline(iss, token, '-'))
std::cout << token << std::endl;

return 0;
}

关于c++ - 获取总线错误 : 10 with string append,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21928988/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com