打印出所有名称
Print out all of name
我使用指针打印该程序的字符串数组的内容,我在打印出项目名称时遇到问题。无论我输入多少个项目,它都只打印出一个项目。例如,当我输入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;
}
}
相关文章:
- 当在同一名称空间中有两个具有相同签名的函数时,会发生什么
- 有一个打印语句的函数是一种糟糕的编程实践吗
- 如何仅使用对象名称打印特定于对象的成员
- 为什么 c++(g++) 不允许模板返回类型和函数名称之间有空格?
- 有没有将变量名称转换为双指针的简短方法?
- 重载 std::字符串运算符+ 用于打印枚举名称
- 如何获取列表的每个对象并调用getName方法来打印其名称
- 将C++函数名称打印为 C,无需修饰
- 为什么 GCC 无法优化,除非返回值有名称?
- 非 OOP 版本的"财产"是否有名称?
- 是否有任何打印2D阵列C 的快捷方式
- 一个人可以使用clang ast使用名称打印功能指针的质量
- C++:此模式是否有名称,是否可以改进
- 按作为字符串内容接收的名称打印字符串
- 是否有用于打印源文件直接包含的标题的 GCC 选项
- 为什么不能按名称打印成员函数的地址?
- 检查是否有多个字符串为空并打印它们的名称
- 此方法是否已经有名称
- 像"__LINE__"一样,C/C++ 中是否有任何打印线程名称或 ID 的标准宏?
- 哪些右值有名称