打印一行 2D 字符数组 (C++)
Printing a row of 2d char array (C++)
所以我声明了一个 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 中的字符串由