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

ex11.1

// ex_11.1
#include 
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 
#include 
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 
#include 
#include 
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

 

你可能感兴趣的:(C++,c,C语言,C,Primer,Plus,第六版,练习,自学)