[英]C - Read and parse method not getting second line of input
我正在编写一个程序,处理存储在Matrix结构中的方程组。 目的是读取以下格式的行
1 2 3, 2 3 4
并具有相当于
x + 2y = 3
2x + 3y = 4
目前仅存储
x + 2y = 3
进入我的矩阵
我有一种蓝图,通常用于解析C语言中的输入,但是为了适应此分配,我不得不偏离它一点,我猜测内循环的标记化过程出了点问题,并且破坏了原始设计输入。
相关代码:
#define delims " \t\r\n"
Matrix createMatrix()
{
Matrix m = malloc(sizeof(Matrix));
char *input, c;
int len = 0, max = 1;
char *row, *coeff;
int rows = 0, cols;
bool set = false;
printf("\n: ");
input = malloc(max);
// get input from user
while ((c = getc(stdin)) != '\0' && c != '\n')
{
input[len++] = c;
if (len == max)
{
input = realloc(input, 2*max);
max *= 2;
}
}
// parse input into equation by (,) delimiter
row = strtok(input, ",");
do
{
cols = 0;
// parse equation into coefficients by space delimiter
coeff = strtok(row, delims);
setCoeff(m, rows, cols++, atoi(coeff) / 1.0);
while ((coeff = strtok(NULL, delims)) != NULL)
{
setCoeff(m, rows, cols++, atoi(coeff) / 1.0);
}
coeff = strtok(NULL,delims);
rows++;
if (!set)
{
setCols(m, cols);
set = true;
}
else
assert(cols == m->cols);
}
while ((row = strtok(NULL, ",")) != NULL);
row = strtok(NULL, ",");
setRows(m, rows);
return m;
}
矩阵
#include <stdio.h>
#include <stdlib.h>
#ifndef MATRIX_H_INCLUDED
#define MATRIX_H_INCLUDED
typedef struct Matrix
{
int rows;
int cols;
double coeff[26][27];
} *Matrix;
void setRows(Matrix m, int r);
void setCols(Matrix m, int c);
void setCoeff(Matrix m, int row, int col, double val);
#endif // MATRIX_H_INCLUDED
矩阵
#include <stdio.h>
#include <stdlib.h>
#include "Matrix.h"
void setRows(Matrix m, int r)
{
m->rows = r;
}
void setCols(Matrix m, int c)
{
m->cols = c;
}
void setCoeff(Matrix m, int row, int col, double val)
{
m->coeff[row][col] = val;
}
您使用strtok
两次:一次读取逗号分隔的数据,然后在内部读取值。 您的while条件将使用为其赋予的最新指针,即值读取器,因此它无法为您找到更多的行。
您必须先读取行,然后读取值,或者对这些值使用单独的方法,而不是对两者都使用strtok
。
strtok
保持内部状态以跟踪其剩余位置。 这就是为什么您应该在初次调用时传递原始字符串,但是在后续调用中使用NULL
调用它的原因。 您正在尝试交错对strtok
独立调用,因此它将无法在第一个调用和后续调用之间进行适当的区分。
相反,您可以尝试使用strtok_r
(由POSIX指定的strtok
的可重入版本,它不依赖于全局状态,从而避免了此问题;在Windows上,等效功能为strtok_s
)或strsep
如果您的平台支持的话); 都不是标准C的一部分。
如果您需要可移植性,则需要重组代码,以便分别执行解析阶段:首先完全解析所有用','
分隔的标记,跟踪结果,然后在第二阶段解析' '
-从每个先前结果中分隔符号。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.