《C Primer Plus》第11章复习题与编程练习

C Prime Plus编程练习(第十一章) 1. 设计并测试一个函数,从输入中获取下n个字符(包括空白、制表符、换行符),把结果储存在一个数组里,它的地址被传递作为一个参数 #include <stdio.h> #include <string.h> #define STRLEN 20 int main(void) { char words[STRLEN]; int spaceNum = 0... 阅读详情

《C Primer Plus》第11章复习题与编程练习

复习题

1. 下面字符串的声明有什么问题?

这不是一个字符串,而是一个字符数组。
应该在末尾加上’\n’,或这样声明:char name[] = “Fess”;

2. 下面的程序会打印什么?

#include <stdio.h> 
int main(void) 
{ 
    char note[] = "See you at the snack bar."; 
    char *ptr; 
    ptr = note; 
    puts(ptr); 
    puts(++ptr); 
    note[7] = '\0'; 
    puts(note); 
    puts(++ptr); 
    return 0; 
}

See you at the snack bar.

ee you at the snack bar.

See you

e you

3. 下面的程序会打印什么?

#include <stdio.h> 
#include <string.h> 
int main(void) 
{ 
    char food [] = "Yummy"; 
    char *ptr; 
    ptr = food + strlen(food); 
    while (--ptr >= food) 
        puts(ptr); 
    return 0; 
}

y
my
mmy
ummy
Yummy

4. 下面的程序会打印什么?

#include <stdio.h> 
#include <string.h> 
int main(void) 
{ 
    char goldwyn[40] = "art of it all "; 
    char samuel[40] = "I read p"; 
    const char * quote = "the way through."; 
    strcat(goldwyn, quote); 
    strcat(samuel, goldwyn); 
    puts(samuel); 
    return 0; 
}

I read part of it all the way through.

5. 下面的练习涉及字符串、循环、指针和递增指针。首先,假设定义了下面的函数:

#include <stdio.h> 
char *pr(char *str) 
{ 
    char *pc; 
    pc = str; 
    while (*pc) 
        putchar(*pc++); 
    do 
    {
        putchar(*--pc); 
    }while (pc - str); 
    return (pc); 
}

考虑下面的函数调用: x = pr(“Ho Ho Ho!”);
a.将打印什么?
b.x是什么类型?
c.x的值是什么?
d.表达式*–pc是什么意思?与–pc有何不同?
e.如果用
pc–替换*–pc,会打印什么?
f.两个while循环用来测试什么?
g.如果pr()函数的参数是空字符串,会怎样?
h.必须在主调函数中做什么,才能让pr()函数正常运行?

a. Ho Ho Ho!!oH oH oH

b. char*

c. 第一个H的地址

d. 当前指针所指元素的前一个元素的值;后者的值为当前元素的值 - 1

e. Ho Ho Ho! !oH oH o

f. 前者检查 pc 是否指向一个空字符,后者检查 pc 是否与 str 指向相同的位置(即字符串的开头)

g. 第一个循环检测为空不执行,第二个循环pc递减指向空字符前面的存储区,并把其中的内容当做字符打印,此后pc将不会等于str,这个循环过程将一直持续

h. 声明pr(): char *pr(char *);

6. 假设有如下声明:

char sign = ‘$’;

sign占用多少字节的内存?
’ $ ’ 占用多少字节的内存?
“$” 占用多少字节的内存?

char型变量占一个字节。
字符型常量一般当做int型存储,一般是2或4个字节,我所用的编译器是4个字节。
字符串占2个字节,除了’$'还有一个空字符占一个字节。

7. 下面的程序会打印出什么?

#include <stdio.h> 
#include <string.h> 
#define M1 "How are ya, sweetie? " 
char M2[40] = "Beat the clock."; 
char * M3 = "chat"; 
int main(void) 
{ 
    char words[80]; 
    printf(M1); 
    puts(M1); 
    puts(M2); 
    puts(M2 + 1); 
    strcpy(words, M2); 
    strcat(words, " Win a toy."); 
    puts(words); 
    words[4] = '\0'; 
    puts(words); 
    while (*M3) 
        puts(M3++); 
    puts(--M3); 
    puts(--M3); 
    M3 = M1; 
    puts(M3); 
    return 0;
}

How are ya, sweetie? How are ya, sweetie?
Beat the clock.
eat the clock.
Beat the clock. Win a toy.
Beat
chat
hat
at
t
t
at
How are ya, sweetie?

8. 下面的程序会打印出什么?

#include <stdio.h> 
int main(void) 
{ 
    char str1 [] = "gawsie"; 
    char str2 [] = "bletonism"; 
    char *ps; 
    int i = 0; 
    for (ps = str1; *ps != '\0'; ps++) 
    { 
        if (*ps == 'a' || *ps == 'e') 
            putchar(*ps); 
        else 
            (*ps)--; 
        putchar(*ps); 
    } 
    putchar('\n'); 
    while (str2[i] != '\0') 
    { 
        printf("%c", i % 3 ? str2[i] : '*'); 
        ++i; 
    } 
    return 0; 
}

在这里插入图片描述

9. 本章定义的s_gets()函数,用指针表示法代替数组表示法便可减少一个变量i。请改写该函数。

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

10. strlen()函数接受一个指向字符串的指针作为参数,并返回该字符串的长度。请编写一个这样的函数。

int sl(char* st)
{ 
    int n = 0;
    while(*st++)
    {
        n++;
    }
    return n;
}

11. 本章定义的s_gets()函数,可以用strchr()函数代替其中的while循环来查找换行符。请改写该函数。

char* s_gets(char* st, int n)
{ 
    char* ret_val;
    int i = 0;
    ret_val = fgets(st, n, stdin);
    if (ret_val)
    {
        char* f = strchr(st, '\n');
        if (f)
            *f = '\0';
        else
            while (getchar() != '\n')
                continue;
    }
    return ret_val;
}

12. 设计一个函数,接受一个指向字符串的指针,返回指向该字符串第1个空格字符的指针,或如果未找到空格字符,则返回空指针。

char* fs(char* st)
{ 
    while(*st++)
    {
        if(*st == ' ')
        {
            return st;
        }
    }
    return NULL;
}

13. 重写程序清单11.21,使用ctype.h头文件中的函数,以便无论用户选择大写还是小写,该程序都能正确识别答案。

#include <stdio.h>
#include <string.h>  // strcmp()函数的原型在该头文件中
#include <ctype.h>
#define ANSWER "grant"
#define SIZE 40
char * s_gets(char * st, int n);
 
char* tl(char* a)
{
    char* b = a;
    while(*a)//不能写*a++或者*++a, 其效果都是递增一位再解引用
    {
        *a = tolower(*a);
        a++;
    }
    return b;
}
 
int main(void)
{
    char try[SIZE];
    puts("Who is buried in Grant's tomb?");
    s_gets(try, SIZE);
    while (strcmp(tl(try), ANSWER) != 0)
    {
        puts(try);
        puts("No, that's wrong. Try again.");
        s_gets(try, SIZE);
    }
    puts("That's right!");
    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 (getchar() != '\n')
                continue;
    }
    return ret_val;
}

编程练习

1. 获取下n个字符

设计并测试一个函数,从输入中获取下n个字符(包括空白、制表符、换行符),把结果储存在一个数组里,它的地址被传递作为一个参数。

代码:

#include <stdio.h>
#include <stdlib.h>
void get_n_char(char *, int);
int main(void)
{
    int n;
    printf("Enter the number of char: ");
    scanf("%d", &n);
    getchar();

    char arr[n + 1];
    printf("Enter n characters: ");
    get_n_char(arr, n);
    printf("arr: ");
    puts(arr);

    system("pause");
    return 0;
}
void get_n_char(char *a, int n)
{
    for (int i = 0; i < n; i++)
        a[i] = getchar();
    a[n] = '\0';
}

2. 修改并编程练习1的函数

修改并编程练习1的函数,在n个字符后停止,或在读到第1个空白、制表符或换行符时停止,哪个先遇到哪个停止。不能只使用scanf()。

代码:

#include <stdio.h>
#include <stdlib.h>
void get_n_char(char *, int);
int main(void)
{
    int n;
    printf("Enter the number of char: ");
    scanf("%d", &n);
    getchar();

    char arr[n + 1];
    printf("Enter n characters: ");
    get_n_char(arr, n);
    printf("arr: ");
    puts(arr);

    system("pause");
    return 0;
}
void get_n_char(char *a, int n)
{
    for (int i = 0; i < n; i++)
    {
        a[i] = getchar();
        if (a[i] == ' ' || a[i] == '\n' || a[i] == '\t')
            break;
    }
    a[n] = '\0';
}

3. 把一个单词读入一个数组

设计并测试一个函数,从一行输入中把一个单词读入一个数组中,并丢弃输入行中的其余字符。该函数应该跳过第1个非空白字符前面的所有空白。将一个单词定义为没有空白、制表符或换行符的字符序列。

代码:

#include <stdio.h>
#include <stdlib.h>
#define STRLEN 100
void get_word(char *);
int main(void)
{
    char arr[STRLEN];

    get_word(arr);
    puts(arr);

    system("pause");
    return 0;
}
void get_word(char *a)
{

    char ch;
    
    while ((ch = getchar()) <= ' ')
        continue;
    while (ch > ' ')
    {
        *a = ch;
        a++;
        ch = getchar();
    }
}

4. 把单词读入数组,设置最大字符数

设计并测试一个函数,它类似编程练习3的描述,只不过它接受第2个参数指明可读取的最大字符数。

代码:

#include <stdio.h>
#include <stdlib.h>
void get_word(char *, int);
int main(void)
{
    int n;
    printf("Enter maximum number of characters: ");
    scanf("%d", &n);
    char arr[n + 1];

    get_word(arr, n);
    puts(arr);

    system("pause");
    return 0;
}
void get_word(char *a, int n)
{

    char ch;
    int i = 0;

    while ((ch = getchar()) <= ' ')
        continue;
    while (ch > ' ' && i++ < n)
    {
        *a = ch;
        a++;
        ch = getchar();
    }
}

5. 查找字符首次出现的位置

设计并测试一个函数,搜索第1个函数形参指定的字符串,在其中查找第2个函数形参指定的字符首次出现的位置。如果成功,该函数返指向该字符的指针,如果在字符串中未找到指定字符,则返回空指针(该函数的功能与 strchr()函数相同)。在一个完整的程序中测试该函数,使用一个循环给函数提供输入值。

代码:

#include <stdio.h>
#include <stdlib.h>
#define STRLEN 100
char *index(char *, char);
int main(void)
{
    char str[STRLEN];
    char ch;
    char *ch_index;

    printf("Enter the string: ");
    gets(str);
    printf("Enter the character: ");
    scanf("%c", &ch);
    ch_index = index(str, ch);
    if (ch_index != NULL)
        printf("I found it! %c is in %p.\n", *ch_index, ch_index);
    else
        printf("%c doesn't exist in the string.\n", ch);

    system("pause");
    return 0;
}
char *index(char *str, char c)
{
    while (*str)
    {
        if (*str == c)
            return str;
        else
            str++;
    }
    return NULL;
}

6. is_within()

编写一个名为is_within()的函数,接受一个字符和一个指向字符串的指针作为两个函数形参。如果指定字符在字符串中,该函数返回一个非零值(即为真)。否则,返回0(即为假)。在一个完整的程序中测试该函数,使用一个循环给函数提供输入值。

代码:

#include <stdio.h>
#include <stdlib.h>
#define STRLEN 100
int is_within(char *, char);
int main(void)
{
    char str[STRLEN];
    char ch;

    while (true)
    {
        printf("Enter the string: ");
        gets(str);
        printf("Enter the character: ");
        scanf("%c", &ch);
        if (is_within(str, ch))
            printf("%c exist in the string.\n", ch);
        else
            printf("%c doesn't exist in the string.\n", ch);
    }

    system("pause");
    return 0;
}
int is_within(char *str, char c)
{
    while (*str)
    {
        if (*str == c)
            return 1;
        else
            str++;
    }
    return 0;
}

7. mystrncpy()

strncpy(s1, s2, n)函数把s2中的n个字符拷贝至s1中,截断s2,或者有必要的话在末尾添加空字符。如果s2的长度是n或多于n,目标字符串不能以空字符结尾。该函数返回s1。自己编写一个这样的函数,名为mystrncpy()。在一个完整的程序中测试该函数,使用一个循环给函数提供输入值。

代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define STRLEN 100
char *mystrncpy(char *, char *, int);
int main(void)
{
    char s1[STRLEN];
    char s2[STRLEN];
    int n;

    while (true)
    {
        printf("Enter s1: ");
        scanf("%s", s1);
        printf("Enter s2: ");
        scanf("%s", s2);
        printf("Enter n: ");
        scanf("%d", &n);
        mystrncpy(s1, s2, n);
        printf("after copying, s1: %s\n", s1);
    }

    system("pause");
    return 0;
}
char *mystrncpy(char *str1, char *str2, int n)
{
    char *s = str1;
    while (*str2 && n--)
    {
        *str1 = *str2;
        str1++;
        str2++;
    }
    if (n)
        *str1 = '\0';
    return s;
}

8. string_in()

编写一个名为string_in()的函数,接受两个指向字符串的指针作为参数。如果第2个字符串中包含第1个字符串,该函数将返回第1个字符串开始的地址。例如,string_in(“hats”, “at”)将返回hats中a的地址。否则,该函数返回空指针。在一个完整的程序中测试该函数,使用一个循环给函数提供输入值。

代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define STRLEN 100
void get_nextval(const char *t, int a[], int n);
char *string_in(char *s1, char *s2);
int main(void)
{
    char s1[STRLEN];
    char s2[STRLEN];

    while (true)
    {
        printf("Enter s1: ");
        scanf("%s", s1);
        printf("Enter s2: ");
        scanf("%s", s2);
        char *x = string_in(s1, s2);
        if (x)
            printf("s1 obtains s2, the address of the beginning %c is %p.\n", *x, x);
        else
            printf("s1 doesn't exist s2.\n");
    }

    system("pause");
    return 0;
}
void get_nextval(const char *t, int a[], int n)
{
    int i = 0, j = -1;
    a[0] = -1;
    while (i < n)
    {
        if (j == -1 || t[i] == t[j])
        {
            ++i;
            ++j;
            if (t[i] != t[j])
                a[i] = j;
            else
                a[i] = a[j];
        }
        else
            j = a[j];
    }
}
char *string_in(char *s1, char *s2)
{
    int n2 = 0, n1 = 0;
    char *a = s2;
    while (*a)
    {
        n2++;
        a++;
    }
    a = s1;
    while (*a)
    {
        n1++;
        a++;
    }
    int next[n2];
    get_nextval(s2, next, n2);
    int i = 0, j = -1;
    while (i < n1 && j < n2)
    {
        if (j == -1 || s1[i] == s2[j])
        {
            ++i;
            ++j;
        }
        else
            j = next[j];
    }
    if (j == n2)
        return &s1[i - n2];

    return NULL;
}

9. 反序字符串

编写一个函数,把字符串中的内容用其反序字符串代替。在一个完整的程序中测试该函数,使用一个循环给函数提供输入值。

代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define STRLEN 100
void swap(char *, char *);
void reverse(char str[]);
int main(void)
{
    char s[STRLEN];

    printf("Enter a string: ");
    scanf("%s", s);
    reverse(s);
    printf("reverse: %s\n", s);

    system("pause");
    return 0;
}
void swap(char *a, char *b)
{
    char temp = *a;
    *a = *b;
    *b = temp;
}
void reverse(char str[])
{
    int len = strlen(str);
    for (int i = 0; i < len / 2; i++)
        swap((str + i), (str + len - 1 - i));
}

10. 删除字符串中的空格

编写一个函数接受一个字符串作为参数,并删除字符串中的空格。在一个程序中测试该函数,使用循环读取输入行,直到用户输入一行空行。该程序应该应用该函数读取每个输入的字符串,并显示处理后的字符串。

代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define STRLEN 100
void remove_space(char *str);
int main(void)
{
    char s[STRLEN];

    printf("Enter a string: ");
    gets(s);
    remove_space(s);
    printf("All thr spaces are removed: %s\n", s);

    system("pause");
    return 0;
}
void remove_space(char *str)
{
    int begin = 0;
    int end = 0;
    while (str[end] != '\0')
    {
        if (str[end] != ' ')
        {
            str[begin] = str[end];
            begin++;
            end++;
        }
        else
            end++;
    }
    str[begin] = '\0';
}

11. 字符串打印菜单

编写一个函数,读入10个字符串或者读到EOF时停止。该程序为用户提供一个有5个选项的菜单:打印源字符串列表、以ASCII中的顺序打印字符串、按长度递增顺序打印字符串、按字符串中第1个单词的长度打印字符串、退出。菜单可以循环显示,除非用户选择退出选项。当然,该程序要能真正完成菜单中各选项的功能。

代码:

#include <stdio.h>
#include <string.h>
#include <stdbool.h>
#define LIM 10
#define SIZE 100
char *s_gets(char *st, int n);
char menu(void);
void print_origin(char ar[][100], int n);
void print_sort(char *ar[], int n);
void print_len(char *ar[], int n);
void print_first(char *ar[], int n);
int length(char *ar);
int main(void)
{
    char st1[LIM][SIZE];
    char *pt1[LIM];
    int ct = 0;
    printf("Please input the strings, EOF to quit.\n");
    while (ct < LIM && s_gets(st1[ct], SIZE) != NULL && st1[ct][0] != EOF)
    {
        pt1[ct] = st1[ct];
        ct++;
    }
    char ch = menu();
    while (ch != 'q')
    {
        switch (ch)
        {
        case 'a':
            print_origin(st1, ct);
            break;
        case 'b':
            print_sort(pt1, ct);
            break;
        case 'c':
            print_len(pt1, ct);
            break;
        case 'd':
            print_first(pt1, ct);
            break;
        case 'q':
            printf("Bye!\n");
            break;
        default:
            printf("\nI can only understand a, b, c, d, q.\n");
        }
        ch = menu();
    }
    return 0;
}

char menu(void)
{
    char ch;

    printf("Please input your choice:\n");
    printf("-----------------------------------------------------\n");
    printf("a) print origin         b) print sort by ASCII\n");
    printf("c) print by length      d) print by first word length\n");
    printf("q) quit\n");
    printf("-----------------------------------------------------\n");
    
    ch = getchar();
    while (getchar() != '\n')
        continue;
    return ch;
}

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 (getchar() != '\n')
                continue;
    }
    return ret_val;
}

void print_origin(char ar[][100], int n)
{
    int i;
    puts("\nShow the origin: ");
    for (i = 0; i < n; i++)
    {
        puts(ar[i]);
    }
    putchar('\n');
}

void print_sort(char *ar[], int n)
{
    char *temp;
    int i, j;

    for (i = 0; i < n - 1; i++)
    {
        for (j = i + 1; j < n; j++)
        {
            if (strcmp(ar[i], ar[j]) > 0)
            {
                temp = ar[i];
                ar[i] = ar[j];
                ar[j] = temp;
            }
        }
    }
    puts("\nHere is the sorted by ASCII:");
    for (i = 0; i < n; i++)
    {
        puts(ar[i]);
    }
    putchar('\n');
}

void print_len(char *ar[], int n)
{
    char *temp;
    int i, j;

    for (i = 0; i < n - 1; i++)
    {
        for (j = i + 1; j < n; j++)
        {
            if (strlen(ar[i]) > strlen(ar[j]))
            {
                temp = ar[i];
                ar[i] = ar[j];
                ar[j] = temp;
            }
        }
    }
    puts("\nHere is show by length: ");
    for (i = 0; i < n; i++)
    {
        puts(ar[i]);
    }
    putchar('\n');
}

void print_first(char *ar[], int n)
{
    char *temp;
    int i, j;

    for (i = 0; i < n - 1; i++)
    {
        for (j = i + 1; j < n; j++)
        {
            if (length(ar[i]) > length(ar[j]))
            {
                temp = ar[i];
                ar[i] = ar[j];
                ar[j] = temp;
            }
        }
    }
    puts("\nShow the result sort by first word:");
    for (i = 0; i < n; i++)
    {
        puts(ar[i]);
    }
    putchar('\n');
}

int length(char *ar)
{
    int i = 0;
    int j = 0;
    bool inword = false;

    while (ar[i] != '\0')
    {
        if (inword == false && ar[i] != ' ')
            inword = true;
        if (inword == true && ar[i] != ' ')
            j++;
        if (inword == true && ar[i] == ' ')
            break;
        i++;
    }

    if (j != 0)
        return j;
    else
        return i;
}

12. 统计字符数

编写一个程序,读取输入,直至读到 EOF,报告读入的单词数、大写字母数、小写字母数、标点符号数和数字字符数。使用ctype.h头文件中的函数。

代码:

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
void basic(void);
int main(void)
{
    char ch;
    int words = 0;
    int upper = 0;
    int lower = 0;
    int punct = 0;
    int digit = 0;
    bool is_word = false;

    printf("please input strings(EOF to quit): \n");
    while ((ch = getchar()) != EOF)
    {
        if (!isspace(ch) && is_word == false)
        {
            words++;
            is_word = true;
        }
        if (isspace(ch) && is_word == true)
            is_word = false;
        if (isupper(ch))
            upper++;
        if (islower(ch))
            lower++;
        if (ispunct(ch))
            punct++;
        if (isdigit(ch))
            digit++;
    }
    printf("words: %d\n", words);
    printf("upper: %d\n", upper);
    printf("lower: %d\n", lower);
    printf("punct: %d\n", punct);
    printf("digit: %d\n", digit);

    system("pause");
    return 0;
}

13. 反序显示命令行参数的单词

编写一个程序,反序显示命令行参数的单词。例如,命令行参数是 see you later,该程序应打印later you see。

代码:

#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
    printf("The command line has %d arguments.\n", argc - 1);
    printf("Print them in reversed order:\n");
    for (int i = 1; i < argc; i++)
        printf("%s ", argv[argc - i]);
    putchar('\n');

    system("pause");
    return 0;
}

14. 命令行运行程序计算幂

编写一个通过命令行运行的程序计算幂。第1个命令行参数是double类型的数,作为幂的底数,第2个参数是整数,作为幂的指数。

代码:

#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
    float base = atof(argv[1]);
    int power = atoi(argv[2]);
    double sum = 1;

    if (argc != 3)
        printf("arguments error!\n");
    else
    {
        for (int i = 0; i < power; i++)
            sum *= base;
        printf("result: %lf\n", sum);
    }

    system("pause");
    return 0;
}

15. myatoi()

使用字符分类函数实现atoi()函数。如果输入的字符串不是纯数字,该函数返回0。

代码:

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <typeinfo>
#define STRLEN 100
int my_atoi(char *);
int main(void)
{
    char s[STRLEN];

    printf("Enter a string: ");
    scanf("%s", s);
    if (my_atoi(s))
    {
        printf("turn to integer: %d.\n", my_atoi(s));
        printf("my_atoi(s) is %s.\n", typeid(my_atoi(s)).name());
    }
    else
        printf("not all digits!\n");

    system("pause");
    return 0;
}
int my_atoi(char *str)
{
    int n = 0;
    while (*str)
    {
        n *= 10;
        if (!isdigit(*str))
            return 0;
        else
        {
            n += *str - '0';
            str++;
        }
    }
    return n;
}

16. 识别和实现命令行参数,打印字符串

编写一个程序读取输入,直至读到文件结尾,然后把字符串打印出来。该程序识别和实现下面的命令行参数:
-p 按原样打印
-u 把输入全部转换成大写
-l 把输入全部转换成小写
如果没有命令行参数,则让程序像是使用了-p参数那样运行。

代码:

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#define STRLEN 100
void print_original(char *);
void print_upper(char *);
void print_lower(char *);
int main(int argc, char *argv[])
{
    char ch;
    char str[STRLEN];

    if (argc == 1)
        ch = 'p';
    else if (argc == 2)
        ch = argv[1][1];
    if (argc <= 2)
    {
        printf("Enter a string: ");
        scanf("%s", str);
        switch (ch)
        {
        case 'p':
        case 'P':
            print_original(str);
            break;
        case 'u':
        case 'U':
            print_upper(str);
            break;
        case 'l':
        case 'L':
            print_lower(str);
            break;
        }
    }
    else
        printf("arguments error!\n");

    system("pause");
    return 0;
}

void print_original(char *str)
{
    printf("result: %s\n", str);
}

void print_upper(char *str)
{
    int i = 0;

    while (str[i])
    {
        str[i] = toupper(str[i]);
        i++;
    }
    printf("result: %s\n", str);
}

void print_lower(char *str)
{
    int i = 0;

    while (str[i])
    {
        str[i] = tolower(str[i]);
        i++;
    }
    printf("result: %s\n", str);
}
C Primer Plus 第十一章 字符串 编程练习答案(自作) 阅读详情

相关推荐

《C Primer Plus》第 11 章复习题和编程练习

《C Primer Plus》第 11 章复习题和编程练习

潇雪的博客 1132

C Primer Plus编程练习_第十一章(菜鸟版)

1.设计并测试一个函数,从输入中获取下n个字符(包括空白、制表符、换行符),把结果储存在一个数组里,它的地址被传递作为一个参数 // 1.子函数,从输入中获取下n个字符,结构存储在一个数组里 #include <stdio.h> void read(char *s1, int n); int main() { char ch[128] = "";//空串 int n = 5; read(ch, n); for (int i = 0; i < n; i++) { printf(

Zeroninetozero的博客 1120

C primer plus 复习题答案(上)

C primer plus 复习题答案 第一章 初识C语言 ​ 对编程而言,可移植性意味着什么 在软件工程中,可移植性,又译为移植性、可携性,是指使用高阶语言写成的软件,在不同环境下,是否具备可以被重复使用的性质。一般来说,软件是否具备可移植性的衡量标准,在于进行软件移植时,需要付出多少工时为代价。具备高可移植性的软件,在移植到不同系统平台时,并不需要做太多事情,因此能够减少软件开发及布署时的成本。为了使软件具备高度可移植性,程序员需要使应用程序界面抽象化以及模组化。 以低阶语言,例如汇编语言,写成的软

Jonathan的博客 3万+

编写一个程序,读取输入,直至读到EOF,统计读入的单词数、大写字母数、小写字母数、标点符号数和数字字符数。使用ctype.h头文件中的函数。

编写一个程序,读取输入,直至读到EOF,统计读入的单词数、大写字母数、小写字母数、标点符号数和数字字符数。使用ctype.h头文件中的函数。

weixin_55347379的博客 348

C primer plus编程练习答案(上)

个人学习总结 C primer plus上篇

Jonathan的博客 7123

C Primer Plus第4章编程题

printf()和scanf()的*修饰符 C Primer Plus第4章编程题

weixin_62428401的博客 1488

gdb调试(2):断点

转发自:http://songjinshan.com/akabook/zh/gdb.html#id1看以下程序: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15#include &lt;stdio.h&gt; int main(void) { int sum = 0, i = 0; char input[5]; ...

XiAoma123_1的专栏 840

C++ Primer Plus(第六版)编程练习答案 第11章 使用类

本章所有编程练习的工程源码可在此处下载(点击此链接下载),供大家参考交流!   1. 修改程序清单11.5,使之将一系列连续的随机漫步者位置写入到文件中。对于每个位置,用步号进行标示。另外,让该程序将初始条件(目标距离和步长)以及结果小结写入到该文件中。该文件的内容与下面类似: (……代码省略……) 本题要求将随机漫步者的位置写入到文件中,这些内容刚好和程序清单11.13,11.14,11...

清水河C罗——Leonardo-Liu 5299

C Primer Plus(第6版) 第十一章 编程练习及部分复习题参考答案

C Primer Plus(第6版) 第十一章 编程练习及部分复习题参考答案 编译环境:Microsoft Visual Studio 2019 备注:本文留作作者自用,如有错误敬请指出 (针对Microsoft Visual Studio 2019的一些特性对答案进行了修改) 复习题 9.本章定义的s_gets()函数,用指针表示法代替数组表示法便可减少一个变量i。请改写该函数。 10. strlen()函数接受一个指向字符串的指针作为参数,并返回该字符串的长度。请编写一个这样的函数。 11.本章义的s_

weixin_51614848的博客 885

爬取中国空气质量在线监测分析平台

1.准备,爬取的链接地址 https://www.aqistudy.cn/html/city_detail.html 2.分析 a.当打开链接后,数据已经设置好了,说明里面大部分都是js通过ajax调用的, b.打开f12分析代码 通过捕获到的数据包,发现当前请求为ajax,携带着一个为d的参数且该请求携带的数据是加密过的,并且响应也是加密过的 c.这时候的问题就是...

Mr Right 6375

Matlab编码转换实战:从GBK到UTF-8的完整解决方案

本文提供Matlab编码转换的完整实战方案,重点解决GBK与UTF-8编码冲突导致的中文乱码问题。通过修改系统配置文件、批量转换项目文件及设置默认保存编码,实现从GBK到UTF-8的彻底迁移,并分享常见避坑指南与自动化脚本技巧,确保代码跨平台协作的稳定性。

weixin_29031057的博客 331

c++ primer plus(第6版)中文版 第十一章编程练习答案

11.1修改程序清单11.5,将一系列连续的随机漫步者位置写入文件中,另外将初始条件和结果小结写入文件 //TVector.h #include namespace n_vector { using std::ostream; class TVector { public: enum Mode {RECT, POL}; // 坐标类型,依次为直角坐标、极坐标 public:

gd275313的专栏 2319

《C Primer Plus》第 8 章复习题和编程练习

《C Primer Plus》第 8 章复习题和编程练习

潇雪的博客 1415

避坑指南:LISFLOOD-FP模型数据单位、参数文件与results文件夹结果解析全攻略

本文详细解析了LISFLOOD-FP洪水模拟模型的关键应用环节,包括数据单位校验、参数文件优化及结果文件解读与可视化。特别针对常见的单位混淆问题,提供了从DEM到边界条件的全面校验方法,并深入剖析了.par参数文件的配置技巧,帮助用户避免模型崩溃和结果失真。

weixin_42533622的博客 245

CVPR2021 CenterPoint源码解读:从VoxelNet到两阶段优化的完整实现细节

本文深度解析了CVPR 2021 CenterPoint模型的完整实现细节,从VoxelNet体素化、稀疏卷积Backbone,到基于中心点的检测头与两阶段精修机制。文章提供了从环境搭建、数据预处理到核心代码模块(如热力图生成、关键点特征提取与MLP Refiner)的实战指南,并分享了训练策略、多任务损失调优及可视化调试等关键工程实践,助力开发者深入理解并复现这一高效的3D目标检测框架。

linux的博客 473

《C Primer Plus》第10 章复习题和编程练习

《C Primer Plus》第 10 章复习题和编程练习

潇雪的博客 1521

开源ISP介绍(1)——开源ISP的Vivado框架搭建

ZYNQ视频图像处理系统,ISP图像处理硬件实现

路漫漫其修远兮,吾将上下而求索 3296

《C Primer Plus》第10章复习题与编程练习

《C Primer Plus》第10章复习题与编程练习

ProgramNovice的博客 1144

ISO13849功能安全从入门到精通(3):安全功能及其对降低风险的贡献4

例如,如果机器必须在有限速度下运行时进行设置,那么在低加速度值下进行设置时,参数P1将是正确的选择:随着危险缓慢出现并给予足够的运动自由,操作员将能够移出危险区域。例如,在无故障的条件下,在操作者的手的方向移动的滚子不能陷住它。在所有其他情况下,F1是正确的选择,前提是危险暴露的持续时间不超过机器总操作时间的1/20。需求来源于必要的风险降低。由于这些考虑而降低的PLr在任何情况下都不得低于通过比较方式考虑的机器的PLr,因为并不能从事故发生率低和严重程度低得出实施的安全功能提供的安全水平高于要求。

wdconan001的博客 838

高创伺服的龙门调试经历2

摘要:本文介绍了高创伺服在龙门控制中的配置方法。首先通过ServoStudio2连接驱动器并命名区分主从轴(MASTER/DIFF),然后设置接口模式、23位编码器参数及极限位置。重点说明龙门模式的三项关键参数设置(gantryfbenmode=1、gantrymode=1/2)和连线状态确认。建议单轴自动整定后调整从轴增益(如0.2),并强调带刹车电机的同步控制要点:刹车线需接同一继电器由主轴控制,避免位置偏差。

wzz418550729的博客 939

《C Primer Plus》第 2 章复习题和编程练习

《C Primer Plus》第 2 章复习题和编程练习

潇雪的博客 1568

最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版

Part-E1-SDIO-Specification-Ver4.00-Final-120220.pdf:最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版,包括SDIO 接口的外设,SDIO 接口官方协议等。

C Primer Plus (中文版)第11章编程练习 参考答案(仅供参考~)

C Primer Plus (中文版)第11章编程练习 参考答案(仅供参考~)

成为富婆,报效祖国!! 2024

lwip-2.0.3

lwip是瑞典计算机科学院(SICS)的Adam Dunkels 开发的一个小型开源的TCP/IP协议栈。实现的重点是在保持TCP协议主要功能的基础上减少对RAM 的占用。

怀旧版电脑GBC模拟器

再现原版GBC掌机的界面,电脑运行连游戏界面都一样大小,很怀旧,很真实,(英文版)强烈推荐,很小的文件,很难才找到的。

《C Primer Plus》第 9 章复习题和编程练习

《C Primer Plus》第 9 章复习题和编程练习

潇雪的博客 1477

RU DOS版、EFI版32bit/64bit BIOS常用工具

DOS版、EFI版的RU工具,可用来查看IO、MEM、PCI、SMBIOS等资源。亲测在EFI SHELL下可用。

《C Primer Plus》第9章复习题与编程练习

《C Primer Plus》第9章复习题与编程练习

ProgramNovice的博客 840

《C Primer Plus》第7章复习题与编程练习

《C Primer Plus》第7章复习题与编程练习

ProgramNovice的博客 1157
上一篇: Windows 环境下 Hadoop 的安装和配置
下一篇: 《大数据:互联网大规模数据挖掘与分布式处理》(第二版)第一章习题答案
UestcXiye
博客等级 码龄8年 9044粉丝 1306原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

UestcXiye

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值
⌂ 换网址