如何在c ++中填充指针数组,键入char?

时间:2016-02-15 21:34:40

标签: c++ arrays pointers char

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

1 个答案:

答案 0 :(得分:1)

您改为使用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);
    }
}