【问题标题】:String is out of range字符串超出范围
【发布时间】:2021-12-30 09:34:01
【问题描述】:

任务是交换一个单词的两个部分,其中包含破折号(即我们有 1237-456,但应该将其转换为 456-1237)。这是我的代码,它运行但不显示结果,因为字符串超出范围,我知道为什么。它发生在第一次,第二次迭代以错误结束+它发生在 strlen 为 5 或更多时。代码:

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

int main()
{
    int u = 0, y = 0;
    string first, second;
    int i = 0;
    string word;
    cout << "Enter the text: " << endl;
    getline(cin, word);
    int l = size(word);
    int f = word.find('-');
    cout << "The word has " << l << " characters" << endl << endl;
    for (int i = 0; i < f; i++) {
        first[i] = word[i];
    }
    for (int i = f + 1; i < l; i++) {
        second[y] = word[i];
        y++;
    }
    cout << endl << second << " - " << first << endl;
}

【问题讨论】:

  • 我看不到你在代码中的哪里初始化了firstsecond的长度,所以它们的初始长度仍然是0。尝试访问空字符串的任何元素似乎是错误的
  • firstsecond 是空字符串,因此 first[i]second[y] 是非法的。你应该使用.push_back()。我想它在任何 C++ 书籍中都有讲授。

标签: c++ string


【解决方案1】:

不要访问 first 和 second 的元素,只需尝试使用 .push_back() 从 word 中添加字符。

【讨论】:

  • 没有改变
【解决方案2】:

first 和 second 不会分配内存。它们被初始化为大小为 0 的字符串。对于这种情况,我将只使用迭代器而不是索引(尽管它们也可以工作,但是您需要更多的手动工作来为目标字符串和所有字符串分配足够的空间)。 总而言之,我认为您的代码有点混合了“c”和“c++”风格,所以这是我的例子:

#include <algorithm> // for find
#include <iostream>

// #include <cstdlib> // <<== this is "c" not C++
// using namespace std; <<== unlearn this

int main()
{
    std::string word{ "Mississippi-delta"};

    // std::string has a lenght function use that
    std::cout << "The word has " << word.length() << " characters\n";
    
    // "it" will be an iterator to the location of '-' (if any)
    auto it = std::find(word.begin(), word.end(), '-');
    
    // it points (beyond) the end of the word if no '-' is found
    if (it == word.end())
    {
        std::cout << "no '-' found in word";
    }
    else
    {
        std::string first{ word.begin(),it };
        ++it; // skip '-'
        std::string second{ it,word.end() };

        std::cout << second << "-" << first << "\n";        
    }

    return 0;
}

【讨论】:

  • 虽然我是新手,但你看,我已经读过使用 std 是一个不好的迹象,但还没有理解为什么,至于现在我认为我应该学习原则。然后才写没有std或紧急开始?
  • 最好现在学习,以后再学习,特别是如果它们很容易,比如键入 std::。忘记模式比学习模式更难。早点学习的好东西:使用 std::vector/std::array (通过'C'样式数组),避免新/删除,使用引用(更喜欢指针),抽象基类(接口)。并且不要试图用继承来解决所有问题,组合也是面向对象的。 (我知道这很多,只是在学习 C++ 时将其放在脑海中)。永远不要忘记,正确的编程很有趣!
  • 能否请您提供一些书籍供新手学习,以便从中开始
  • 说实话,我不知道有什么好书。对我来说,阅读任何 C++(初学者)书籍已经太久了。我在 1995 年开始编写 C++ 代码;)不久前我确实看过 Jason Turner 的这段视频,虽然非常好:youtube.com/watch?v=iz5Qx18H6lg。它涉及许多重要的事情
猜你喜欢
  • 2012-06-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-31
  • 2016-05-18
  • 2013-05-13
相关资源
最近更新 更多