【问题标题】:Why am I getting a segmentation error? What is the reason getting output as numbers instead of strings?为什么我会收到分段错误?将输出作为数字而不是字符串的原因是什么?
【发布时间】:2017-05-09 22:07:49
【问题描述】:

我知道为什么会出现分段错误,但我无法使用以下代码找出错误,该代码是基于空格分割字符串的。

#include<iostream>
#include<string>
#include<vector>
#include<typeinfo>
using namespace std;
vector<string> split(const string& s)
{
    //cout << "HERE";
    vector<string> tab;
    for(unsigned int a = 0; a < s.size(); a++)
    {
        string temp = to_string(s[a]);
        while(to_string(s[a]) != " ")
        {
            a++;
            temp = temp + s[a];
        }
        tab.push_back(temp);
    }
    return tab;
}   


int main()
{
    int n;
    cin >> n;

    while(n--)
    {
        string s;
        cin >> s;
        vector<string> temp = split(s);
        for(unsigned int i = 0; i < temp.size(); i++)
        {
            cout << temp[i] << endl;
        }
    }
    return 0;
}

另外,如果我在 split 函数中注释掉 while 循环,我会在打印出结果字符串时得到数字。是因为to_string吗?如果我在主函数中打印得到的结果字符串上使用typeid(variable).name(),我会得到:NSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE

【问题讨论】:

  • 程序应该做什么?另外,你好像是在Linux上,有没有试过用gdb?
  • std::string::findstd::string::substr 够你用了
  • 这些标签真的有必要吗?
  • 回到你的问题,std::to_stringchar 没有超载

标签: c++ string c++11 vector


【解决方案1】:

回答你的最后一个问题:

C++ 经常(但并非总是)将char 值视为数字,如果您将其传递给to_string,肯定会这样做。所以to_string(' ') 将返回"32"(通常),这是转换为十进制字符串的空格的字符代码。

要将字符转换为相应的单元素字符串,请使用例如string(1, ' ').

对于您的分段错误,调试器是正确的工具。

【讨论】:

    【解决方案2】:

    您的拆分功能有问题。您的程序将始终崩溃,因为 while 循环上的 while(to_string(s[a]) != " ") 条件会导致无限循环。

    您使用 to_string(s[a]) 对我来说似乎很奇怪。假设 s[a] 实际上是空格字符,即使在这种情况下 toString(" ") 将返回一个包含“32”的 std::string。并且“32”不等于“”,所以这将导致你的循环无限运行。

    并且由于在循环中您正在增加索引,如下所示。

        a++;  ---> You increase the index in infite loop so a can go to millions 
        temp = temp + s[a]; ---> you are using the index and causing index out of range. 
    

    您将导致索引超出范围错误。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-16
      • 1970-01-01
      • 2023-02-21
      • 1970-01-01
      • 2020-01-10
      相关资源
      最近更新 更多