|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
题目
要求 A:定义一个长度为 21 的字符数组,用于存放用户输入的文本;
要求 B:如果用户输入的文本长度超过 20 个字符,且文本中存在空格,则截取至最接近末尾(第 20 个字符串)的空格;
要求 C:如果用户输入的文本长度超过 20 个字符,且文本中不存在空格,则打印前 20 个字符。
- #include <stdio.h>
- #include <string.h>
- /*统计每个单词的字符数储存在b
- *将单词字符数跟空格统计到a
- 判断如果a 《 20,则为位最接近末尾的空格,打印。
- * 将读取的字符储存在ls里如果下一个字符跟上一个都不为空格则符合超
- 过20个字符且不存在空格,直接打印即可 */
- int main()
- {
- char str1[21], 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[21] = '\0';
- }
- if(ch != ' ')
- {
- b = b + 1;
- ls = ch;
- if(ls != ' ' && ch != ' ')
- {
- strncpy(str1, ch, 20);
- str1[21] = '\0';
- }
- }
- if(ch == ' ')
- {
- a = a + b + 1;
- b = 0;
- if(a < 20)
- {
- strncpy(str1, ch, a);
- str1[21] = '\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
请问为什么?哪里出现了问题?谢谢大佬
|
|