【问题标题】:Function converting char[] to array is not returning right value将 char[] 转换为数组的函数没有返回正确的值
【发布时间】:2016-03-05 19:43:34
【问题描述】:

我需要编写一个程序,以 [num1 num2; 形式从用户那里获取矩阵。 num 3 num4 etc] 与指向已创建表的指针一起传递(另一个函数计算行和列并创建适当的数组),然后将其转换为数组。我不知道为什么,将 char 转换为 int 的部分会产生疯狂的数字。 IE。对于输入 [1 3] 它返回 1 作为第一个位置和超过 20000 的第二个位置。

void string_to_table(int **matrix,char text[])
{
    printf("start");
    int len=strlen(text);
    int out=0;
    int column=0;
    int row=0;
    int pos=1;
    int j=1;
    while(j<(len-1))
    {
        if(text[j]=='-')
            pos=-1;
        else if(text[j]>='0'&&text[j]<='9')
        {
            out=out+pos*(text[j]-48);
        }
        else if(text[j]==' ')
        {
            matrix[column][row]=out;
            out=0;
            pos=1;
            ++row;
        }
        else if(text[j]==';')
        {
            matrix[column][row]=out;
            out=0;
            pos=1;
            ++column;
            row=0;
        }
        else if(text[j]=='}')
            break;
        ++j;
    }
}

*编辑我使用的打印

void print_da_matrix(int **matrix, int i, int j)
{
    int k=0,l=0;
    printf("[");
    while(k<i)
    {
        while(l<j)
        {
            printf("%i",matrix[k][l]);
            printf(" ");
            ++l;
        }
        if(k<(i-1))
            printf(";");
        l=0;

            ++k;
    }
    printf("]");
}

其中 i 和 j 是列数和行数。

【问题讨论】:

  • 为什么你认为第二个元素超过20000?你打印出数组的内容了吗?如果是这样,请显示执行此操作的代码行。

标签: c multidimensional-array char int type-conversion


【解决方案1】:
out=out+pos*(text[j]-48);

应该是

out = out*10 + pos*(text[j]-'0');

你还需要对不跟在数字后面的空格做点什么,比如';'后面的那个

【讨论】:

  • 不过,第二个数字还是疯了。它给出了一些随机的大数字
  • 第二个数字后面有空格吗?您的代码忽略了“]”
  • 没有。当它到达位置 len -1,即 ']' 时结束
  • 结束,但如果没有空格或';'则不保存
  • 非常感谢。当我将最后一个 if 替换为 if(text[j]==']') matrix[column][row]=out;在 len-1 到 len 开始工作
猜你喜欢
  • 2011-02-17
  • 1970-01-01
  • 1970-01-01
  • 2019-11-28
  • 2017-08-22
  • 1970-01-01
相关资源
最近更新 更多