【发布时间】:2021-08-29 10:15:28
【问题描述】:
Newb:学习 C - 使用 C 编程语言 - 第 2 版。 我已经搜索了 stackoverflow - 找不到解决方案。
我正在使用 getchar() 打开一个流(这是手册让我学习的内容。流以 EOF <ctrl> z 结尾。脚本查找新行并将每一行放入一个二维数组(行, width) 每行都应该包含一整行输入。
代码运行,流工作。虽然似乎没有填充数组。代码远未完善,只是在我完善之前试图让它工作。我只是将 exit() 用作尝试使其正常工作的捷径。有任何想法吗?我添加了一个计数器,它在末尾打印r,它应该指示在数组中创建的行数......它为零......让我觉得数组没有被构建。宇宙的命运取决于你!!!
#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
#define ROW 1000
#define WIDTH 5000
char arr[ROW][WIDTH] = {0}; // array to store char strings of sentences - each sentence stored in an individual row
int r = 0; // initiallizing rows
int i = 0;
char endprog(char arr[ROW][WIDTH]);
int main () {
int c; // int variable to accept input - will be copied into arraw
bool end = true; // count the character for each line to iterate through
while (end){
for ( i = 0; i < (c = getchar()) != EOF && c != '\n'; ++i){
if (c == EOF)
endprog(arr);
arr[r][i] = c;
if (c == '\n'){
arr[r][i] = c;
i++;
r++; // new line deterted row incremented to next row - ready for new line
}
arr[r][i] = '\0'; // copying input into array at position (row, i)
}
}
}
char endprog(char arr[ROW][WIDTH]){
int j;
for (j = 0; j <= r; j++){ // iterating through array to print rows of input strings
printf("R: %d", r);
printf("%s\n", arr[j]);
}
exit(0);
}
输出
Stream is working.
New lines are accepted
Help me Obi-Wan Kenobi
You're my only hope....
^Z
R: 0
--------------------------------
Process exited after 120.8 seconds with return value 0
Press any key to continue . . .
【问题讨论】:
-
inner
if条件没有意义 - 您已经在for条件中确保c != \n... -
我知道。书中的例子两者都有,它需要一些清理。我只是无法填充数组...我不认为内部
if是罪魁祸首...我会尝试... -
@OrenIshShalom - 内部
if做的比我想象的要多....所以现在我得到每行的第一个字母作为输出...r值是 62这似乎是字符总数……离从帝国手中拯救共和国又近了一步! -
您的行总是 是否包含
WIDTH条目?或者它们可以小于该值?如果他们总是有WIDTH条目,你最好用双嵌套循环读取你的矩阵...... -
不,它们可以更短... WIDTH 仅用于内存分配...最终我将编码最大宽度..等等...