c++ - 这段代码在 C++ 中的问题是什么?我必须使用 c-string
问题描述
我创建了一个 c 字符串数组。此代码接受三个字符串的输入,然后将其显示在控制台上。但不幸的是,输入很好,但输出显示不起作用。
int main()
{
char *str[20];
std::cout << "Enter values to strings: ";
for (int i = 0; i < 3; i++)
{
std::cout << "\nstr" << i<<": ";
std::cin >> str[i];
}
std::cout << "\n\n\nouput:";
for (int i = 0; i < 3; i++)
{
std::cout << "\nstr" << i<<":";
std::cout << str[i];
}
return 0;
}
解决方案
正如评论中提到的,使用未初始化的指针是未定义的行为。如果您需要使用 C 字符串(即您不能使用std::string
,我通常会推荐),只需使用 为您的 C 字符串分配内存operator new
。一种可能的方法是定义预期输入字符串的一些恒定最大长度,将输入读取到缓冲区,然后分配必要的内存并将数据复制到新分配的空间:
#include <iostream>
#include <cstring>
constexpr int MAX_STR_LEN = 255;
int main()
{
char *str[20];
char buff[MAX_STR_LEN]; // going to read strings here and copy them to `str` array
std::memset(buff, 0, MAX_STR_LEN); // fill the buffer with zeroes
std::cout << "Enter values to strings: ";
for (int i = 0; i < 3; i++)
{
std::cout << "\nstr" << i<<": ";
std::cin >> buff;
str[i] = new char[std::strlen(buff)+1]; // +1 for terminating null
std::memcpy(str[i], buff, std::strlen(buff));
str[i][std::strlen(buff)] = 0; // last character should be null
}
std::cout << "\n\n\nouput:";
for (int i = 0; i < 3; i++)
{
std::cout << "\nstr" << i<<":";
std::cout << str[i];
delete[] str[i];
}
return 0;
}
请注意,此示例仅用于练习目的,通常 C++ 开发人员会使用std::vector<std::string>
来保持字符串的动态数组。
推荐阅读
- javascript - 异步等待节点中的特定事件
- python - 从 python 写入 Excel 电子表格
- spring - 如何配置客户端使用 spring 2.4.1 和 cloud 2020.0.0?
- javascript - Vuejs 在标签中结合 HTML
- javascript - 如何在本机反应中通过发布请求将插入添加到数据组件中
- python - 在每个重复的 ID 前插入新行
- javascript - 无限滚动实现不适用于移动浏览器
- javascript - Nodejs从日志文件中提取所有ipAddress
- python - 如何实时更新 tkinter 标签文本
- angular - 错误 TS2739:“AbstractControl”类型缺少“FormControl”类型的以下属性:registerOnChange、registerOnDisabledChange