gpt4 book ai didi

c - 在C中将字符串读入二维数组

转载 作者:行者123 更新时间:2023-11-30 20:31:11 26 4
gpt4 key购买 nike

我想使用 getchar() 将多个字符串从文本文件(标准输入)读取到二维数组。请忽略代码中的魔数(Magic Number)。

#include <stdio.h>
#include <stdlib.h>

int
main(int argc, char *argv[]) {

char string[100][20];
int c, j = 0, i = 0;

while ((c = getchar()) != EOF) {
while (c != '\n') {
string[j][i] = c;
i++;
}
string[j][i] = '\0';
j++;
}
printf('string is: %s', string);

return 0;
}

最佳答案

您需要在内部 while 循环中再使用一个 getchar()

while (c != '\n') {
string[j][i] = c;
i++;
c = getchar(); /* this you need here to fetch char until \n encounters */
}

一旦此 string[j][i] = '\0'; 完成,需要再次创建变量 i 0

还有这个

printf('string is: %s', string);

是错误的。应该是

printf("string is: %s", string); /* use double quotation instead of single */

示例代码

int main(int argc, char *argv[]) {

char string[100][20];
int c, j = 0, i = 0;

while ((c = getchar()) != EOF) { /* this loop you need to terminate by pressing CTRL+D(in linux) & CTRL+Z(in windows) */
while (c != '\n') { /* this loop is for 1D array i.e storing char into each 1D array */
string[j][i] = c;
i++;
c = getchar(); /* add this, so that when you press ENTER, inner while loop fails */
}
string[j][i] = '\0';
j++;
i = 0;/* make it zero again, so that it put char into string[j][0] everytime once 1 line is completed */
}
for(int row = 0;row < j;row++) { /* rotate loop j times since string is
2D array */
printf("string is: %s", string[row]);
}

return 0;
}

关于c - 在C中将字符串读入二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52343601/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com