如何遍历字符串转ASCII并动态存储?C++11代码无输出排查
问题解答
一、技术咨询:遍历字符串数组并将字符转为ASCII值存入动态内存的实现思路
- 针对单个字符串:先获取字符串长度,用
new关键字分配对应大小的动态内存;遍历每个字符,通过强制类型转换(int)字符得到ASCII值,存入动态数组;使用完毕后用delete[]释放内存,避免泄漏。 - 针对字符串数组:遍历数组中的每个字符串,对每个字符串重复上述单个字符串的处理逻辑即可。
二、问题排查:用户输入后程序无输出的原因及修复
问题根源
你在获取用户输入之前就计算了message_input的长度l,此时message_input是空字符串,l的值为0,后续循环条件i < l直接不成立,循环体完全没执行,所以没有输出。而直接赋值字符串时,message_input有内容,l能得到正确长度,循环正常运行。
修复后的代码
#include <iostream> #include <string> using namespace std; int main() { string message_input{}; cout << "type in your message " << endl; // 先获取用户输入,再计算字符串长度 getline(cin, message_input); int l = message_input.length(); double* ascii_storage = new double[l + 1]{}; for (int i = 0; i < l; ++i) { ascii_storage[i] = static_cast<int>(message_input[i]); cout << "the values inside the ascii baskii " << ascii_storage[i] << endl; } // 释放动态分配的内存,防止内存泄漏 delete[] ascii_storage; return 0; }
额外优化建议
- 尽量避免
using namespace std;,改用std::前缀,减少命名冲突风险 - 强制类型转换推荐用
static_cast<int>代替C风格的(int),类型安全性更高 - 若使用C++11及以上版本,更推荐用
std::vector<double>代替手动管理动态数组,无需手动释放内存,更安全便捷:
#include <iostream> #include <string> #include <vector> int main() { std::string message_input{}; std::cout << "type in your message " << std::endl; std::getline(std::cin, message_input); std::vector<double> ascii_storage; for (char c : message_input) { ascii_storage.push_back(static_cast<int>(c)); std::cout << "the values inside the ascii baskii " << ascii_storage.back() << std::endl; } return 0; }
内容的提问来源于stack exchange,提问作者THE BLACKSMITH
相关产品推荐
相关产品推荐

