【发布时间】:2017-05-14 03:00:12
【问题描述】:
我对编码还很陌生,目前正在学校学习 C 语言的编程课程。我们被分配了一项作业,我在第一部分遇到了一些困难。我们正在学习如何使用字符串处理库 (stdlib.h),作业的目标是从键盘输入多行文本。导师建议我们使用二维数组来做到这一点,但我有点卡住了。这是我写的代码:
int main(void) {
char string[3][SIZE];
int i, j;
int c;
printf("Enter three lines of text:\n");
for (i = 0; i < 3; i++) {
j = 0;
while ((j < SIZE) && (c = getchar() != '\n')) {
string[i][j] = c;
j++;
}
}
for (i = 0; i < 3; i++) {
for (j = 0; j < SIZE; j++) {
printf("%c", string[i][j]);
}
printf("\n");
}
return 0;
}
我想说明的几点是,我使用 getchar() 函数一次接收一个字符的输入,以及第二个 for 循环,我打算打印存储在每一行中的每一行文本的字符串数组。
输入是三行的任意文本字符串,例如:
Hi my name is John.\n
I am from the US\n
and I'm a student.
这是当前输出的样子:
Enter three lines of text:
rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr...
我期待的输出是:
Enter three lines of text:\n
Hi my name is John.\n
I'm from the US\n
and am a student.
任何提示或建议将不胜感激。谢谢!
【问题讨论】:
-
逐字练习是练习的要求吗?
-
是的!这就是我使用 getchar() 函数的原因。我的导师推荐,因为我们正在研究字符串处理库,我们尝试尽可能多地利用它,无论是否合适或效率。
-
修复this
-
这个
c = getchar() != '\n'不符合您的预期。