【问题标题】:Why is this code only evaluating first character when its in a for loop C为什么此代码仅在 for 循环 C 中评估第一个字符
【发布时间】:2014-09-03 12:42:18
【问题描述】:

为什么这段代码只计算 datatest 的第一个字符?我需要它来测试字符串是否仅包含字母数字字母和空格字符并将其存储在 records.data 中。 rCount 是记录的计数。这一切都按预期工作,除了 islanum 和 isspace 函数,它只评估字符串中的第一个字符并存储它。方法很好,除了我希望它对整个字符串执行此操作,而不仅仅是第一个字符。 如果数据包含除字母数字字符或空格以外的任何内容,我会将其存储在其他位置

for (i=0; i<=datalength; i++)
{
    if ((sourceint < 1025 && sourceint >0)&&
    (portint <1025 && portint >0) &&
    (typeint < 11 && typeint >=0) &&
    (destinationint <1025 && destinationint >0) &&
    (datalength < 51) &&
    (isalnum(datatest[i]) ||  isspace(datatest[i])))
    {
        records[*rCount].destination = destinationint;
        records[*rCount].type = typeint;
        records[*rCount].port = portint;
        records[*rCount].source = sourceint;

        for (i=0; i<=datalength; i++)
        {
            records[*rCount].data[i] = datatest[i];
            records[*rCount].data[i+1] = '\0';
        }

        printf("VALID DATA FROM STRUCT - %i - %i - %i - %i - %s\n", records[*rCount].source, records[*rCount].destination, records[*rCount].type, records[*rCount].port, records[*rCount].data);
    }
}

【问题讨论】:

    标签: c validation for-loop struct


    【解决方案1】:

    因为您使用变量 i 作为两个 for() 循环的迭代器。尝试使用不同的变量。内部循环直到i &gt; datalength,这导致外部循环也终止,因为它使用相同的条件。

    【讨论】:

    • 每次我改变一些东西似乎都搞砸了。我需要在第二个 for 循环中更改数组的值吗?我为函数做了它与初始 for 循环相同,但它只是多次打印数据
    • 我不知道你真正想要什么。但是第二个循环应该更像for (j = 0; j &lt;= datalength; ++j) { ... data[j] ... }。不要忘记在某处声明int j;
    【解决方案2】:

    当两个 for 循环在另一个循环中时,它们使用相同的变量。 基本上 i 为 0,然后它在内部循环中,并且 i 为 0 并达到数据长度,在第一次运行时,我将转向数据长度。只需声明一些其他整数,例如 j 或您喜欢的任何内容。 另外,rcount 保持不变,你每次都去数组中的同一个位置,也许这​​就是你打算做的,试试rCount++;

    【讨论】:

      猜你喜欢
      • 2011-12-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-17
      • 1970-01-01
      • 2021-07-01
      • 1970-01-01
      • 2011-01-30
      相关资源
      最近更新 更多