程序中的分段错误,该错误从字符串创建向量 [英] Segmentation fault in program which creates a vector from a string

查看:132
本文介绍了程序中的分段错误,该错误从字符串创建向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在以下程序中出现了细分错误。

为什么会发生这种情况,我该如何解决?

I got a Segmentation fault in the following program.
Why is this happening and how can I fix it?

#include <string>
#include <vector>
#include <iostream>
#include <algorithm>

std::vector<std::string> split_words(std::string s) {
    std::vector<std::string> v(1, "");
    int i=0;
    int wortanzahl = 0;
    while(i<s.size()) {
        if (s[i]!=' ') {
            v.resize(wortanzahl + 1, "");
            for (int j=i; s[j]!=' '; ++j) {
                v[wortanzahl] += s[j];
                i=j;
            }
            ++wortanzahl;
        }
        ++i;
    }
}

int main() {
    std::string s = "Alpha beta! Gamma";
    split_words(s);
    return 0;
}


推荐答案


我不知道原因

I don't know the reason

您的代码有几个问题。一个明显的问题是您没有在 split_words 函数中返回向量 v 。不从定义为要返回值的函数中返回值是未定义行为

You have several issues with your code. The one glaring one is that you failed to return the vector v in the split_words function. Not returning a value from a function that is defined to return a value is undefined behavior.

第二个问题是 j 落在最后一个单词的末尾,因为循环仅在 s [j] 为空白时停止。字符串不是以空字符结尾,因此循环会超出字符串的长度。

The second issue is that j falls off the end on the last word, since your loop only stops on s[j] being a blank. The string does not end on a blank character, thus your loop keeps going beyond the length of the string.

话虽如此,如果您的目标是在空格字符上分割字符串,无需编写此类代码即可完成这项工作。相反,只需使用 std :: istringstream operator>>

Having said this, if your goal is to split a string on the space character, there is no need to write code like this to do the job. Instead, simply use std::istringstream and operator >>:

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

std::vector<std::string> split_words(std::string s) 
{
    std::vector<std::string> v;
    std::istringstream iss(s);
    std::string temp;
    while (iss >> temp)
       v.push_back(temp);
    return v;
}
 
int main() 
{
   std::string s = "Alpha beta! Gamma";
   auto vect = split_words(s);
   for (auto& word : vect)
      std::cout << word << "\n";
   return 0;
} 

实时示例

循环简单地在流上调用 operator>> ,每次迭代调用 push_back 每个遇到的已解析字符串。

The loop simply calls operator >> on the stream, and each iteration calls push_back for each parsed string encountered.

这篇关于程序中的分段错误,该错误从字符串创建向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆