如何解决C:将整数读取到动态分配的数组中,并以空格分隔并与其他字符忽略/替换
基本上,我的问题是我试图将Python3可以轻松实现的功能手动转换为C程序。我的第一个障碍是从字面上理解输入。这是示例输入:
5
12
34 10
22 20 55
123 30 x 99
如我们所见,此输入中包含数字,空格和字符。我很容易用Python处理它,就像这样:
n = int(input()) #first line is always a single integer
matrix = [[' ' for i in range(n)] for j in range(n)] #declaring matrix of just space chars
for i in range(1,n):
line = input().split(' ') #gets rid of all spaces
for j in range(len(line)):
try:
matrix[i][j] = int(line[j])
matrix[j][i] = int(line[j]) #mirrors same value on opposite part of the matrix
except:
matrix[i][j] = 'x'
matrix[j][i] = 'x'
这将导致以下矩阵:
[[' ',12,34,22,123]
[12,' ',10,20,30]
[34,55,'x']
[22,99]
[123,30,'x',99,' ']]
所以基本上,我想弄清楚如何用C语言实现。我看过有关如何动态读取输入,如何接收以空格分隔的整数以及如何分配整数空间的文章,但是我不知道如何将所有这些东西放在一起。我非常感谢您的帮助。理想情况下,我想将所有这些整数存储到如上所述的2D整数数组中。
编辑:据我所知(代码是从其他人的有用答案中得出的):
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
int main()
{
int n; //number of cities
scanf("%d",&n);
printf("%d\n",n);
int *matrix = (int*)malloc(n*n*sizeof(int));
int i=0,j=0;
int *line = matrix;
char temp;
for (int k=0;k<n;k++)
{
do {
scanf("%d%c",&line[i],&temp);
i++;
} while(temp != '\n');
for(j=0; j<i; j++) {
printf("%d ",matrix[j]);
}
printf("\n");
}
free(matrix);
free(n);
return 0;
}
此代码的输出:
5
5
12
12
34 10
12 34 10
22 20 55
12 34 10 22 20 55
123 30 x 99
^从上面开始,第一个'5'是我的输入,第二个'5'被输出,第一个'12'是我的输入,第二个输出,依此类推。代码在最后一行中断。我知道每次它都会转储存储在int *矩阵的“缓冲区”中的所有内容。我不知道如何处理'x'等其他字符。理想情况下,我想用-1或其他值替换矩阵中的“ x”。
解决方法
我认为将scanf和getchar混合使用确实是一个错误,但是我认为避免scanf的正确方法是将n
作为参数传递(例如,从argv [1]中读取而不是从中读取)输入流)。另外,您的python并不是一个矩阵,而是一个列表列表,在C实现中使用列表列表可能会更干净。但这是使用大型数组的一种方法。
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
struct entry {
enum { unknown,number,character } type;
union {
int v;
char x;
} value;
};
static int
die(const char *fmt,...)
{
va_list ap;
va_start(ap,fmt);
vfprintf(stderr,fmt,ap);
va_end(ap);
fputc('\n',stderr);
exit(EXIT_FAILURE);
}
int
main(void) {
int n,c = '\n',p = EOF,row = 0;
if( scanf("%d",&n) != 1 || n < 1 ) {
die("Invalid input in row %d (%c)",row,c);
}
struct entry *matrix = calloc(n * n,sizeof *matrix);
struct entry *t = matrix - 1,*e = matrix + n * n;
while( (c = getchar()) != EOF) {
if( isdigit(c) ) {
if( t->type == character ) {
die("Invalid input in row %d (%c)",c);
}
t->type = number;
t->value.v = t->value.v * 10 + c - '0';
} else if( isspace(c) && c != p ) {
t += 1;
if( t >= e ) {
die("Invalid input in row %d (%c)",c);
}
if( c == '\n' ) {
t->type = character;
t->value.x = ' ';
t = matrix + n * ++row;
}
} else {
if( t->type != unknown ) {
die("Invalid input in row %d (%c)",c);
}
t->type = character;
t->value.x = c;
}
p = c;
}
/* Display the matrix */
for( int i = 0; i < n; i++ ) {
for( int j = 0; j < n; j++ ) {
t = matrix + (( j > i ) ? (n * j + i) : (n * i + j));
switch( t->type ) {
case number:
printf("%8d",t->value.v);
break;
case unknown:
printf("%8s","??");
break;
case character:
printf(" '%c'",t->value.x);
}
}
putchar('\n');
}
}
此解决方案不像scanf解决方案那样健壮地解决了输入中的空白问题,并且无法处理空格或混合空格和制表符。剩下的修正工作供读者练习。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。