打印一行 2D 字符数组 (C++)

Printing a row of 2d char array (C++)

本文关键字:字符 数组 C++ 2D 一行 打印      更新时间:2023-10-16

所以我声明了一个 2D 数组,并希望一行一行地显示。但是当我执行以下代码时,我看到矩阵中的所有行都从我需要的行开始。

法典:

#include<iostream.h>
#include<conio.h>
#include<stdio.h>
char topics[3][10]={"Literature","Science---","Sports----"};
void main()
{
    clrscr();
    cout<<topics[0][0]<<endl<<topics[1][0]<<endl<<topics[2][0]<<endl;
    puts(topics[0]);
    cout<<endl;
    puts(topics[1]);
    getch();
}

输出:

L    
S   
S   
LiteratureScience---Sports----         
Science---Sports----

我希望我的程序做的是,当执行 puts(0( 时,只应显示"文学",当执行 puts(1( 时,仅显示"科学---"。

我是初学者。请建议我应该进行哪些更正。谢谢。:)

声明:

char topics[3][10]={"Literature","Science---","Sports----"};

被编译器获取为:

char topics[3][10]={"Literature","Science---","Sports----"};

这意味着这些字符串中的每一个都由 11 个字符组成。

因此,您需要将topics[3][10]更改为 topics[3][11] .

你不需要提到该数组的维度显式。编译器完成这项工作。

const char *topics[] = {"Literature", "Science---", "Sports----"};
int main() {
    puts(topics[0]);
    puts(topics[1]);
}

请注意,通过这种方式,这些字符串是只读的

问题是 C 中的字符串由 终止。因此,您需要11个字符来存储长度为 10 的字符串。如果你的数组太小,最后一个字符会被简单地跳过(参见为什么"字符数组的初始值设定项字符串太长"在 C 中编译得很好,而在 C++ 中编译不行?(。因此,put 不会在字符串的末尾找到,而是转到数组的末尾,因为(幸运的是(数组后面的内存包含零。如前所述,可以修复此问题,使数组大小正确

#include <stdio.h>
char topics[3][11]={"Literature","Science---","Sports----"};
int main()
{
    puts(topics[0]);
    puts(topics[1]);
}

输出为

Literature
Science---

C++编译器不会接受您的程序:

3:59: error: initializer-string for array of chars is too long [-fpermissive]
3:59: error: initializer-string for array of chars is too long [-fpermissive]
3:59: error: initializer-string for array of chars is too long [-fpermissive]

走开。