如何在 c++ 中填充指针数组,类型 char

How can i populate an array of pointers, type char, in c++?

本文关键字:数组 类型 char 指针 填充 c++      更新时间:2023-10-16

例如,让我们有char *names[5] = {"Emanuel", "Michael", "John", "George", "Sam"} .如何使用 for 循环填充 *names[5],使用setw()函数来限制输入字符的数量。

改用C++标准库,特别是std::vectorstd::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);
    }
}