如何在 c++ 中填充指针数组,类型 char
How can i populate an array of pointers, type char, in c++?
例如,让我们有char *names[5] = {"Emanuel", "Michael", "John", "George", "Sam"}
.如何使用 for 循环填充 *names[5],使用setw()
函数来限制输入字符的数量。
改用C++标准库,特别是std::vector
和std::string
:
// empty container of names
std::vector<std::string> names;
// Populated container of names
std::vector<std::string> populatedNames = { "Emanuel", "Michael", "John", "George", "Sam" };
// add some names to both:
names.push_back("Terry");
names.push_back("Foobar");
populatedNames.push_back("Ashley");
// how many names in each?
std::cout << "Our once empty container contains " << names.size() << " names" << std::endl;
std::cout << "Our pre-populated container contains " << populatedNames.size() << " names" << std::endl;
// print names:
for (auto s : names)
{
std::cout << s << std::endl;
}
for (auto s : populatedNames)
{
std::cout << s << std::endl;
}
如果您需要限制名称中的字符,最好在接收输入时执行此操作:
std::string name;
std::getline(std::cin, name);
const auto maxLength = 10;
if (name.length() > maxLength)
{
// inform user that name will be truncated etc, or ask for new name
...
name.erase(maxLength-1);
}
names.push_back(name);
但是,您也可以只循环访问容器并缩短所有名称:
for (auto& s : names)
{
if (s.length() > maxLength)
{
s.erase(maxLength-1);
}
}
相关文章:
- 声明C++具有动态大小的数组类型在 Linux 中工作正常,但不能在 Windows 中工作
- 数组类型 int[n][n] 不可赋值,因为表达式必须具有常量值
- 取消引用结束指针到数组类型的一个
- 结构化绑定初始值设定项表单 { 赋值表达式 } 对于 clang 上的数组类型失败
- 如何在数组类型的模板代码中计算std::size_t
- LLVM 无法将数组类型强制转换为常量数组
- 推荐的方法在不初始化值的情况下使数组类型为 std::unique_ptr?
- 特征:从数组类型中获取标量类型是否记录?
- T D[N] 总是声明数组类型的对象吗?
- 如何在模板中推断数组类型?
- 尝试使用 Array 类的模板构造整数数组时,错误:为什么数组类型"int [5]"不可分配,
- 如何将二维数组类型字符(字符串)作为函数参数传递?
- 如何为所有非数组类型专门化模板?
- 数组类型 (C++) 的初始化
- 我预测char数组类型值只能投射指针类型
- 将数组类型更改为 Int16 会节省存储空间吗?
- 采用通用数组类型的函数
- 数组类型 'int [8]'不可分配
- 数组类型 'float [size]'不可分配
- C++。候选模板被忽略 - 无法将数组类型与自身匹配