gpt4 book ai didi

c - 如何输入n行每行m个字符的字符串,其中可能包含空格作为字符?

转载 作者:行者123 更新时间:2023-11-30 17:10:50 24 4
gpt4 key购买 nike

这是我的代码,它尝试获取号码。行数(n) 和行数
每行中的字符(m)作为输入。但是运行时需要 n 和 m 然后之后不接受任何输入。预期的输入也可能包含空格

 #include<stdio.h>
int main()
{
int n,m,i,j;
scanf("%d%d",&n,&m);
char **a=(char**)malloc(n);
for(i=0;i<m;i++)
a[i]=(char*)malloc(m+1);
for(i=0;i<n;i++)
scanf("%[^\n]%*c", a[i]);
}
/*An example of input would be:
4 4
####
#S #
## #
#E #
*/

最佳答案

松散更正

//    scanf("%d%d",&n,&m);  change to 
scanf("%d %d%*c",&n,&m); // better suggestion

考虑输入格式这是必要的

// char **a=(char**)malloc(n);  change to
char **a=malloc(n * sizeof( char *) );

并且,出于某种原因, m 和 在下面的循环中是混合的

  for(i=0;i<m;i++) 
a[i]=(char*)malloc(m+1);
for(i=0;i<n;i++)
scanf("%[^\n]%*c", a[i]);

更改为

for(i=0;i<n;i++) { // for n pointers
a[i] = malloc ( m * sizeof(char) ); // allocate memory
fgets( a[i], m, stdin ); // scan string
// optionally add this line
//a[ strlen(a[i]) - 1 ] = '\0'; // null terminate optionally
a[i][strcspn(a[i], "\n")] = '\0'; // another awesome suggestion
}

m 的大小是扫描字符串时的关键,确保有足够的字节专门用于 '\n' 和 '\0' 值得分配实际内存 + 2

关于c - 如何输入n行每行m个字符的字符串,其中可能包含空格作为字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32686511/

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