roxas! 发表于 2021-12-12 11:22:38

为什么将ch改成str[count++]和将ch改成str[count]输出的结果会多出一位

本帖最后由 roxas! 于 2021-12-14 12:45 编辑

(本题是求如果用户输入的文本长度超过 20 个字符,且文本中存在空格,则截取至最接近末尾(第 20 个字符串)的空格)
提问:为什么将ch改成str和将ch改成str输出的结果会多出一位
#include<stdio.h>
#include<string.h>

#define MAX 21

int main()
{
      char str;
      int count=0,space,ch;
      
      space = MAX - 1;
      
      printf("请输入一行文本:");
      while ((ch = getchar()) != '\n')∥为什么将ch改成str**替换为视频flash地址****替换为视频flash地址**答案会出错
      {
                //str=ch;
                if(count == MAX-1)
                {
                        break;
                }

                if(ch == ' ')∥为什么将ch改成str答案会出错
                {
                        space=count;
                }      
      }
      
      
      if(count >= MAX-1)
      {
                str = '\0';
                printf("space=%d\n",space);
      }
      else
      {
                str = '\0';
      }

      
      printf("你输入的文本是:%s\n",str);
      return 0;

}
页: [1]
查看完整版本: 为什么将ch改成str[count++]和将ch改成str[count]输出的结果会多出一位