【发布时间】: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;
}
【问题讨论】:
-
我看不到你在代码中的哪里初始化了
first和second的长度,所以它们的初始长度仍然是0。尝试访问空字符串的任何元素似乎是错误的 -
first和second是空字符串,因此first[i]和second[y]是非法的。你应该使用.push_back()。我想它在任何 C++ 书籍中都有讲授。