gpt4 book ai didi

C++ 在我运行我的程序后给我 basic_string::_S_construct null not valid 错误

转载 作者:搜寻专家 更新时间:2023-10-30 23:58:08 24 4
gpt4 key购买 nike

我是 C++ 的新手,我尝试编写一个简单的字符串反向程序。当我编译它时,一切正常,但是当我运行它时,出现以下错误:

terminate called after throwing an instance of 'std::logic_error'
what(): basic_string::_S_construct null not valid
Aborted (core dumped)

我做错了什么?这是我的代码。

#include <iostream>
using namespace std;

string reverse_string(char* argv[], int i);

int main(int argc, char* argv[])
{
for (int i = 0; i < argc; i++)
{
cout << reverse_string(argv, i) << endl;
}
return 0;
}

string reverse_string(char* argv[], int i)
{
string arg = argv[i + 1];
string output;
int length = arg.length();
for (int index = 1; index <= length; index++)
{
output += arg[length-index];
}
return output;
}

最佳答案

这个:argv[i + 1]在你的反向字符串的构造中应该是 argv[i]主循环应该是for (i=1; i<argc; ++i)

还有更简单的方法来反转字符串:

std::string reverse_string(char* argv[], int i)
{
std::string arg = argv[i];
return std::string(arg.rbegin(), arg.rend());
}

关于C++ 在我运行我的程序后给我 basic_string::_S_construct null not valid 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21798951/

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