C++代码出现栈错误,求错误原因及修复方案
问题分析与修复方案
Hey fellow C++ beginner! Let's break down why your code crashes with longer strings and fix it step by step.
核心崩溃原因
- You initialized
n1as an empty string (length 0). When you directly assign values usingn1[i] = '.', this is out-of-bounds memory access. Thestd::stringoperator[]doesn't automatically expand the string's length—short strings might not trigger a crash by chance, but longer ones will definitely mess with invalid memory and cause your program to crash. - A minor side note: Using
endlfor every valid character will print each one on a new line. That's fine if it's what you want, but just wanted to call it out!
两种修复方案
方案一:直接生成目标字符串(推荐,更高效简洁)
Instead of pre-filling with ., we can just append valid characters to n1 as we go. This completely avoids any out-of-bounds issues:
#include<iostream> #include<string> using namespace std; int main(){ string n; string n1; cin >> n; // Use range-based for loop for cleaner traversal for(char c : n) { int ascii_val = static_cast<int>(c); // Check if character is between 'd'(100) and 'n'(110) if(ascii_val > 99 && ascii_val < 111) { n1 += c; } } // Print the final filtered string (remove endl if you don't want a newline) cout << n1 << endl; // If you still need to print each valid character on a new line: // for(char valid_char : n1) { // cout << valid_char << endl; // } return 0; }
方案二:保留 original length, fill invalid positions with .
If you specifically need n1 to match the length of n (with . for invalid characters), we just need to resize n1 first to make all indices valid:
#include<iostream> #include<string> using namespace std; int main(){ string n; string n1; cin >> n; int l = n.length(); // Resize n1 to match n's length, fill all positions with '.' n1.resize(l, '.'); for(int i=0; i<l; i++){ int ascii_val = static_cast<int>(n[i]); if(ascii_val > 99 && ascii_val < 111){ n1[i] = n[i]; } } // Print all non '.' characters for(int i=0; i<l; i++){ if(n1[i] != '.'){ cout << n1[i] << endl; } } return 0; }
Quick Tips
- Using
static_cast<int>(c)to convert a char to its ASCII value is more explicit and safer than direct assignment. - Range-based for loops (
for(char c : n)) make string traversal cleaner and less error-prone than manual index tracking.
内容的提问来源于stack exchange,提问作者whomanx
相关产品推荐
相关产品推荐

