打印出所有名称

时间:2017-01-24 15:34:23

标签: c++

我使用指针打印这个程序的字符串数组的内容,我在打印项目的名称时遇到了麻烦。无论我输入多少项,它只打印出一个项目。例如,当我输入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<<"  ";

}

2 个答案:

答案 0 :(得分:1)

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

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;
}

答案 1 :(得分:0)

有两种可能性:

数组语法

您将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;
  }
}