WwangHB 发表于 2020-2-14 04:54:02

带你学c带你飞s1e19第二题

题目
要求 A:定义一个长度为 21 的字符数组,用于存放用户输入的文本;               
要求 B:如果用户输入的文本长度超过 20 个字符,且文本中存在空格,则截取至最接近末尾(第 20 个字符串)的空格;
要求 C:如果用户输入的文本长度超过 20 个字符,且文本中不存在空格,则打印前 20 个字符。
#include <stdio.h>
#include <string.h>

/*统计每个单词的字符数储存在b
*将单词字符数跟空格统计到a
判断如果a 《 20,则为位最接近末尾的空格,打印。
* 将读取的字符储存在ls里如果下一个字符跟上一个都不为空格则符合超
过20个字符且不存在空格,直接打印即可 */

int main()
{
      char str1, ch;
      int a, b, i = 0;
      char ls;

      a = b = 0;


      printf("请输入一行文本:");
      while((ch = getchar()) != EOF)
      {
                i = i + 1;
                if(i < 20)
                {
                        strncpy(str1, ch, 20);
                              str1 = '\0';
                }
                if(ch != ' ')
                {
                        b = b + 1;
                        ls = ch;
                        if(ls != ' ' && ch != ' ')
                        {
                              strncpy(str1, ch, 20);
                              str1 = '\0';
                        }
                }
                if(ch == ' ')
                {
                        a = a + b + 1;
                        b = 0;
                        if(a < 20)
                        {
                              strncpy(str1, ch, a);
                              str1 = '\0';
                        }
               }

      }

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

      return 0;
}
                                                         

这样写会出现
test1.c: In function ‘main’:
test1.c:19: warning: passing argument 2 of ‘strncpy’ makes pointer from integer without a cast
/usr/include/string.h:131: note: expected ‘const char * __restrict__’ but argument is of type ‘char’
test1.c:27: warning: passing argument 2 of ‘strncpy’ makes pointer from integer without a cast
/usr/include/string.h:131: note: expected ‘const char * __restrict__’ but argument is of type ‘char’
test1.c:36: warning: passing argument 2 of ‘strncpy’ makes pointer from integer without a cast
/usr/include/string.h:131: note: expected ‘const char * __restrict__’ but argument is of type ‘char’
请输入一行文本:Fishc.com
Segmentation fault


请问为什么?哪里出现了问题?谢谢大佬

人造人 发表于 2020-2-14 06:16:44

strncpy(str1, ch, 20);

https://baike.so.com/doc/398560-421965.html

召唤风云 发表于 2020-2-14 07:31:08

应该使用sprintf(),自己去小甲鱼函数快查。

qiuyouzhi 发表于 2020-2-14 08:14:32

用安全函数,普通函数很容易造成内存问题(去C语言的函数快查)

一个账号 发表于 2020-2-14 10:18:00

对,应该用安全函数
页: [1]
查看完整版本: 带你学c带你飞s1e19第二题