C++交换横杠分隔字符串两部分时报string is out of range错误如何解决
问题根源
你代码报错的核心原因是初始化的first、second为空字符串,未提前分配存储空间,直接通过下标赋值属于非法内存访问,触发字符串越界异常。
std::string默认构造得到的是空串,长度为0,任何大于等于0的下标访问都是越界操作。你遇到的「第一个for循环第二次迭代触发报错」就是这个原因:第一次访问first[0]可能因内存分配特性暂时未触发异常,到first[1]就直接触发越界错误,字符串长度越长越容易触发该异常。
同时你的代码还有额外输出格式问题:输出语句里硬编码了横杠前后的空格,最终输出结果会是456 - 1237,和你预期的456-1237不符。
修复方案
方案1:保留循环逻辑,改用push_back追加字符
#include <iostream> #include <string> using namespace std; int main() { string first, second; string word; cout << "Enter the text: " << endl; getline(cin, word); int l = word.size(); int f = word.find('-'); // 增加横杠存在性判断,避免无横杠时出现逻辑错误 if (f == string::npos) { cout << "输入字符串不包含横杠" << endl; return 1; } cout << "The word has " << l << " characters" << endl << endl; for (int i = 0; i < f; i++) { first.push_back(word[i]); } for (int i = f + 1; i < l; i++) { second.push_back(word[i]); } cout << endl << second << "-" << first << endl; return 0; }
方案2:直接用substr截取子串,代码更简洁高效
#include <iostream> #include <string> using namespace std; int main() { string word; cout << "Enter the text: " << endl; getline(cin, word); int f = word.find('-'); if (f == string::npos) { cout << "输入字符串不包含横杠" << endl; return 1; } string first = word.substr(0, f); string second = word.substr(f+1); cout << second << "-" << first << endl; return 0; }
内容的提问来源于stack exchange,提问作者Paw Max1
相关产品推荐
相关产品推荐

