C Primer Plus 第6版 Chapter 11 课后编程练习

10 篇文章 0 订阅

ex11.1

// ex_11.1
#include <stdio.h>
char* gets_n(char* , int);
int main(void)
{
    char* target[80];
    puts("Enter a string:");
    gets_n(target,8);
    puts(target);

    return 0;
}

char* gets_n(char* str, int size)
{
    int i;
    for (i = 0; i < size; i++)
        str[i] = getchar();
    str[i] = '\0';          // 结束字符串
}

ex11.2

// ex_11.2
#include <stdio.h>
#include <string.h>
char* gets_n(char* , int);
int main(void)
{
    char* target[80];
    puts("Enter a string:");
    gets_n(target,8);
    puts(target);

    return 0;
}

char* gets_n(char* st, int n)
{
    char * ret_val;
    int i = 0;
    ret_val = fgets(st, n, stdin);
    if (ret_val && ret_val[0] != ' ' && ret_val[0] != '\n' && ret_val[0] != '\t')
    {
        while (st[i] != ' ' && st[i] != '\t' && st[i] != '\n' && st[i] != '\0')
            i++;
        if (st[i] == '\n')
            st[i] = '\0';
        else
            while (getchar() != '\n')
                continue;
        }
    return ret_val;
}

ex11.3

3. Design and test a function that reads the first word from a line of input into an array and
discards the rest of the line. It should skip over leading whitespace. Define a word as a
sequence of characters with no blanks, tabs, or newlines in it. Use getchar() , not

设计一个函数,读取一行输入后,只把第一个单词放进字符数组。如果第一个字符前有空格、、制表符,跳过,从第一个字符开始算。

#include <stdio.h>
#include <string.h>
#include <ctype.h>
char* s_gets(char* st, int n);

int main(void)
{
    char temp[50];
    s_gets(temp, 50);
    char* new_p = temp;
    int i = 0,j = 0;
    while (isblank(temp[i]))
    {
        i++;
        new_p++;
    }

    char targ[50];
    strncpy(targ, new_p, 49);
    while (j < 49)
    {
        if(isblank(targ[j]))
        {
            targ[j]='\0';
            break;
        }
        j++;
    }
    puts(targ);

    return 0;
}

char* s_gets(char* st, int n)
{
    char* ret_val;
    int i = 0;
    ret_val = fgets(st, n, stdin);

    if(ret_val)
    {
        while(st[i] != '\n' && st[i] != '\0')
            i++;
        if(st[i] == '\n')
            st[i] = '\0';
        else
        {
            while(st[i] != '\n')
                continue;
        }
    }
    return ret_val;
}

ex11.4

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值