【问题标题】:A char array containing strings, and a pointer pointing at that array. How do I loop through it? C++包含字符串的 char 数组和指向该数组的指针。我如何循环遍历它? C++
【发布时间】:2020-05-14 09:01:11
【问题描述】:
#include <iostream>;
using namespace std;

void main() {
    char MONTH_0[] = "January";
    char MONTH_1[] = "February";
    char MONTH_2[] = "March";
    char MONTH_3[] = "April";

    char* pMonth[] = {MONTH_0,MONTH_1,MONTH_2,MONTH_3};

    for (int i = 0; i < 11; i++) {
        cout << *pMonth;
        pMonth[i];
    }
}

大家好,我是 C++ 编码的新手,我得到了一个简单的任务,要按顺序打印全年的月份。我正在寻找一种简洁的方法,所以我想出了一个包含所有月份的 char 数组。 我目前能够毫无问题地打印“January”,但我已经尝试过 pMonth++ 或 pMonth[i] 但没有任何内容会增加下一个 char 数组的指针。谢谢你的时间。 我们不允许使用字符串库!

【问题讨论】:

  • pMonth[i] 是正确的方法。看起来很常见,您在询问代码,但您没有发布不起作用的代码!为什么不呢?
  • 还有12个月for (int i = 0; i &lt; 12; i++) {
  • 除了你的循环访问数组越界(你只有 4 个元素,而不是 11 个),如果你将 cout &lt;&lt; *pMonth; 更改为 cout &lt;&lt; pMonth[i]; 它应该做你想做的事,不是吗?独立的pMonth[i]; 什么都不做
  • 这是由于某些奇怪原因而无法正常工作的代码。它一直在控制台中打印“一月一月一月一月”。
  • @Joints 我很困惑,你说'我试过 pMonth[i]' 然后你会看到使用 'pMonth[i]' 的代码,它解决了问题吗?当你尝试 'pMonth[i]' 时,你到底写了什么?

标签: c++ arrays for-loop char


【解决方案1】:

试试这个:

#include <iostream>

int main() 
{
    char MONTH_0[] = "January";
    char MONTH_1[] = "February";
    char MONTH_2[] = "March";
    char MONTH_3[] = "April";

    char *pMonth[] = {MONTH_0,MONTH_1,MONTH_2,MONTH_3};

    for (size_t i = 0; i < sizeof(pMonth) / sizeof(pMonth[0]); i++)
        std::cout << pMonth[i] << std::endl;
    return 0;
}

或使用std::array

#include <array>
// ...

std::array<std::string, 4> arr = { "January", "February", "March", "April"};
for (const auto& i: arr)
    std::cout << "Month: " << i << std::endl;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-14
    • 2013-03-22
    • 2013-05-20
    • 2018-06-30
    • 2021-05-29
    • 2021-01-26
    • 2020-11-21
    • 1970-01-01
    相关资源
    最近更新 更多