程序不会将字符存储在 c 的二维数组中

Program won't store characters in 2d array in c

我正在创建一个程序,我在其中插入一些句子,然后程序按顺序输出它们。我已经完成了程序,但是当我 运行 时,我输入到数组中的字符似乎没有正确显示或存储,结果得到随机字母而不是完整的句子。这是程序的代码:

char ch;
int i,j,k;
int nothing = 0;
int count = 1;
char lines[5][256];
int length[256];

int main() {
    printf("Please insert up to a max of 5 lines of text (Press enter to go to next line and twice enter to stop the program):\n");
    i = 0;
    while (i<5){

        j = 0;
        ch = getche();

        if (ch == '\r'){
            if(i!= 0){
                break;    
            }
            printf("You have not inserted anything, please insert a line:");
            i=-1;   
        }

        if(ch != '\r'){
            lines[i][j]=ch;
            while (ch!='\r'){
                ch = getche();
                lines[i][j] = ch;
                j++;
            }
        }
        printf("\n");
        i++;
    }
    for (k=i ; k > 0; k--){ 
        printf("\tphrase %i :", count);
        for ( j =0 ; j <= length[k]; j++){
            printf("%c",lines[j][k]);
        }
        count++;
        printf("\n");
    }   
    return 0;
}

如何才能正确存储和显示字符?感谢任何帮助,谢谢!!

您的代码有很多问题。我会尝试在这里总结一下,并给你改进的代码。

首先,为了在我的系统上进行编译,我做了一些更改:

  1. 已将 getche() 更改为 getchar()getche() 似乎在 Ubuntu 上不可用)。
  2. 我去掉了关于重新输入字符串的部分,只关注其余部分(因为那里的逻辑有点破,与你的问题无关)。在继续之前,它仍然会检查至少一行。
  3. 我不得不将 \r 的检查更改为 \n
  4. 我将您的 length 数组更改为大小 5,因为您最多只能有 5 个字符串的长度(而不是 256 个)。

您的代码中存在一些问题:

  1. 您从未在 while 主循环中更新 length[] 数组,因此程序永远不知道要打印多少个字符。
  2. 数组是零索引的,因此您的最终打印循环会跳过字符。我将 for 参数更改为从零开始,一直到 k < i,因为您在上一个循环中的最后一个字符之后更新了 i。与 j.
  3. 相同
  4. 你在打印循环中对数组的引用是错误的(所以你会从内存中的随机区域打印)。将 lines[j][k] 更改为 lines[k][j]
  5. 无需单独的 count 变量 - 只需使用 k。删除了 count.
  6. nothing 变量未被使用 - 将其删除。
#include <stdlib.h>
#include <stdio.h>

char ch;
int i,j,k;
char lines[5][256];
int length[5];

int main()
{
    printf("Please insert up to a max of 5 lines of text (Press enter to go to the next line and twice enter to stop the program):\n");
    i = 0;
    while (i<5)
    {
        j = 0;
        ch = getchar();

        if ((ch == '\n') && (j == 0) && (i > 0))
        {
            break;
        }

        if (ch != '\n')
        {
            while (ch != '\n')
            {
                lines[i][j] = ch;
                j++;
                ch = getchar();
            }
        }
        length[i] = j;
        printf("\n");
        i++;
    }
    for (k = 0; k < i; k++)
    {
        printf("\tPhrase %i : ", k);
        for (j = 0; j < length[k]; j++)
        {
            printf("%c", lines[k][j]);
        }
        printf("\n");
    }
    return 0;
}