字符串长度打印出奇怪的数字。我的代码中的问题在哪里?

问题描述 投票:-3回答:1

我的任务是 写一个不使用库计算字符串长度的程序。

这是我的答案,但在执行过程中出现了一个问题,长度不能正确显示!在我插入的任何字符串中,执行时显示长度为107或127。长度不能正确显示!对于我插入的任何字符串,执行时显示长度为107或127。

#include <stdio.h>
#include <stdlib.h>

int main()
{
   //Declaration of variables :
   char ch[50+1];
   int length, i;

   //data :
   printf("ch : ");
   scanf("%s", &ch);
   printf("\n");

   //Search length of string :
   i = 0;
   do
   {
       if(ch[i] == '\0')
       {
           length = i;
       }
       else
       {
           i++;
       }
   }
   while(ch[i] != '\0');

   //Result "
   printf("length pf %s is : %d \n", ch, length);

   return 0;
} ```
c string loops execution
1个回答
1
投票

有一个问题与算法的。do-while 循环。

计数器 i 状况检查前的增量短。

如果 '\0' 是在下一个数组元素中找到的(注意,该 i 增量)循环立即中断,并且将无法设置 lengthi 在下一次迭代时(因为没有下一次迭代)。

由于 length 未被初始化,程序有 未定义行为.

改为:

do
{
   if (ch[i] == '\0')
   {
       length = i;
   }
   else
   {
       i++;
   }
}
while (ch[i] != '\0');

改为

while (ch[i] != '\0') i++;

length = i;

或者更简单。

while (ch[i] != '\0') length++;

而省去了对号入座 i但你需要初始化 length0 那么。


侧记。

  1. 改变 scanf("%s", &ch);scanf("%s", ch);. - ch 衰减为指向其第一个元素的指针。

  2. 使用长度修饰符在 scanf() -&gt.以确保在用户输入超过50个字符的字符串时不会发生缓冲区溢出。scanf("%50s", ch); 以确保当用户输入一个超过50个字符的字符串时不会发生缓冲区溢出。

  3. 始终检查 scanf() 如果在消耗输入时发生错误。

  4. 千万不要忽略编译器的警告。对于 scanf("%50s", ch); 编译器应该发出警告。

© www.soinside.com 2019 - 2024. All rights reserved.