0

我在下面的这段代码中遇到了一些问题......

代码的主要思想是逐行读取并将 chars 字符串转换为浮点数并将浮点数保存在一个名为nfloat.

输入是一个.txt包含这个:n = 字符串的数量,在这种情况下n = 3

3
[9.3,1.2,87.9]
[1.0,1.0]
[0.0,0.0,1.0]

第一个数字3是我们在图像中看到的向量的数量,但该数字不是静态的,输入可以是5or7等​​而不是3.

到目前为止,我已经开始执行以下操作(仅针对 1 个向量案例),但我认为代码存在一些内存错误:

int main(){
    int n; //number of string, comes in the input
    scanf("%d\n", &n);
    char *line = NULL;
    size_t len = 0;
    ssize_t read;
    read = getline(&line,&len,stdin); //here the program assigns memory for the 1st string
    int numsvector = NumsVector(line, read);//calculate the amount of numbers in the strng
    float nfloat[numsvector];
    int i;
    for (i = 0; i < numsvector; ++i)
    {
        if(numsvector == 1){
            sscanf(line, "[%f]", &nfloat[i]);
        }
        else if(numsvector == 2){
            if(i == 0) {
                sscanf(line, "[%f,", &nfloat[i]);
                printf("%f ", nfloat[i]);
            }
            else if(i == (numsvector-1)){
                sscanf((line+1), "%f]", &nfloat[i]);
                printf("%f\n", nfloat[i]);
            }
        }
    else {   //Here is where I think the problems are
        if(i == 0) {
            sscanf(line, "[%f,", &nfloat[i]);
            printf("%f\n", nfloat[i]);

        }
        else if(i == (numsvector-1)) {
            sscanf((line+1+(4*i)), "%f]", &nfloat[i]);
            printf("%f\n", nfloat[i]);
        }
        else {
            sscanf((line+1+(4*i)), "%f,", &nfloat[i]);
            printf("%f\n", nfloat[i]);
        }
    }
}

好吧,问题来自sscanf我认为的指令,对于带有两个或一个浮点数的字符串,代码可以正常工作,但对于 3 个或更多浮点数,代码不能正常工作,我无法理解为什么...

这里我也附上函数,不过貌似是对的……问题的重点还是在main上。

int NumsVector(char *linea, ssize_t size){
        int numsvector = 1; //minimum value = 1
        int n;
        for(n = 2; n<= size; n++){
            if (linea[n] != '[' && linea[n] != ']'){
                if(linea[n] == 44){
                    numsvector = numsvector + 1;
                }
            }
        }
        return numsvector;
}

请有人帮我理解问题出在哪里?

4

1 回答 1

1

好的 - 如果你用这个替换你当前的 for 循环,你的 nfloat 数组应该以正确的数字结束。

/* Replaces the end ] with a , */
line[strlen(line) - 1] = ',';

/* creates a new pointer, pointing after the first [ in the original string */
char *p = line + 1;
do
{
    /* grabs up to the next comma as a float */
    sscanf(p, "%f,", &nfloat[i]);
    /* prints the float it's just grabbed to 2 dp */
    printf("%.2f\n",nfloat[i]);
    /* moves pointer forward to next comma */
    while (*(p++) != ',');
}
while (++i < numsvector); /* stops when you've got the expected number */
于 2013-10-12T16:53:25.340 回答