【问题标题】:How can i populate an array of pointers, type char, in c++?如何在 C++ 中填充指针数组,类型为 char?
【发布时间】:2016-02-15 21:34:40
【问题描述】:

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

【问题讨论】:

  • 有什么理由不使用std::vector<std::string> 代替吗?
  • “我如何填写*names[5] 访问names[5] 会让你越界。您可以使用的最大索引为 4。

标签: c++ arrays pointers char


【解决方案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);
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-02-14
    • 2013-02-26
    • 1970-01-01
    • 2021-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多