打印出所有名称

Print out all of name

本文关键字:有名称 打印      更新时间:2023-10-16

我使用指针打印该程序的字符串数组的内容,我在打印出项目名称时遇到问题。无论我输入多少个项目,它都只打印出一个项目。例如,当我输入pencil, pen, book时,它只打印了3次最后一项:book book book而不是打印:pencil pen book

void getPrint(string *names, int num){
cout <<"Here is the items you entered: ";
for (int i=0; i<num; i++){
    cout <<*names<<"  ";
}

也许您想将指向单个字符串的指针视为数组:

void getPrint(string * names, int num)
{
  for (int i = 0; i < num; ++i)
  {
    cout << names[i] << " ";
  }
  cout << endl;
}

还有其他可能性:

cout << names++ << " ";
cout << *(names + i) << " ";

收藏的引用中查找指针取消引用。

首选的解决方案是使用 std::vector<string>std::array<string> .

void getPrint(const std::vector<std::string>& names)
{
  const unsigned int quantity = names.size();
  for (unsigned int i = 0; i < quantity; ++i)
  {
    std::cout << names[i] << " ";
  }
  std::cout << endl;
}

有两种可能性:

数组语法

您将 std::string 视为一个数组,并在其索引上递增。为了保持一致性,您也可以在数组语法中传递参数。

void getPrint(const std::string names[], const int num){
    std::cout <<"Here is the items you entered: " << std::endl;
    for (int i=0; i<num; i++){
        std::cout <<names[i]<<"  " << std::endl;
    }
}

指针语法

你传递你的 std::string 作为指针(在数组的第一个元素上)。要访问所有元素,您必须递增指针本身。

void getPrint(const std::string* names, const int num){
    std::cout <<"Here is the items you entered: " << std::endl;
    for (int i=0; i<num; i++){ 
        std::cout <<*(names++)<<"  " << std::endl; // increment pointer
    }
}

由于增加指针不再需要索引 i,因此您可以稍微缩短整个内容(但可能不再声明 const num)。

void getPrint(const std::string* names, int num){
    std::cout <<"Here is the items you entered: " << std::endl;
    while(num--){
        std::cout <<*(names++)<<"  " << std::endl;
    }
}

希望我能帮到你。

编辑

如上所述,任何使用 STL 容器 std::vector 或 std::array 并通过引用传递它们的解决方案都是首选。由于它们提供了 .begin() 和 .end() 方法,因此可以使用 (C++11)

void getPrint(const std::vector<std::string>& names){
    std::cout <<"Here is the items you entered: " << std::endl;
    for (auto name: names){
        std::cout << name << " " << std::endl;
  }
}