if (msg[i] == '\\n') break; }
printf(\ for (i--; i >= 0; i--) putchar(msg[i]); putchar('\\n');
return 0; } (b)
#include
#define MSG_LEN 80 /* maximum length of message */
int main(void) {
char msg[MSG_LEN], *p;
printf(\
for (p = &msg[0]; p < &msg[MSG_LEN]; p++) { *p = getchar(); if (*p == '\\n') break; }
printf(\
for (p--; p >= &msg[0]; p--) putchar(*p); putchar('\\n');
return 0; }
3. [was #8]
#include
#define MSG_LEN 80 /* maximum length of message */
int main(void) {
char msg[MSG_LEN], *p;
printf(\
for (p = msg; p < msg + MSG_LEN; p++) { *p = getchar(); if (*p == '\\n') break; }
printf(\ for (p--; p >= msg; p--) putchar(*p); putchar('\\n');
return 0; }
Chapter 13
Answers to Selected Exercises 2. [was #2]
(a) Illegal; p is not a character. (b) Legal; output is a. (c) Legal; output is abc.
(d) Illegal; *p is not a pointer. 4. [was #4] (a)
int read_line(char str[], int n) {
int ch, i = 0;
while ((ch = getchar()) != '\\n') if (i == 0 && isspace(ch)) ; /* ignore */ else if (i < n) str[i++] = ch; str[i] = '\\0'; return i; }
(b)
int read_line(char str[], int n) {
int ch, i = 0;
while (!isspace(ch = getchar())) if (i < n)
str[i++] = ch; str[i] = '\\0'; return i; } (c)
int read_line(char str[], int n) {
int ch, i = 0;
do {
ch = getchar(); if (i < n)
str[i++] = ch; } while (ch != '\\n'); str[i] = '\\0'; return i; } (d)
int read_line(char str[], int n) {
int ch, i;
for (i = 0; i < n; i++) { ch = getchar(); if (ch == '\\n') break;
str[i] = ch; }
str[i] = '\\0'; return i; }
6. [was #6]
void censor(char s[]) {
int i;
for (i = 0; s[i] != '\\0'; i++)
if (s[i] == 'f' && s[i+1] == 'o' && s[i+2] =='o') s[i] = s[i+1] = s[i+2] = 'x'; }
Note that the short-circuit evaluation of && prevents the if statement from testing characters that follow the null character. 8. [was #10] tired-or-wired?
10. [was #12] The value of q is undefined, so the call of strcpy attempts to copy the string pointed to by p into some unknown area of memory. Exercise 2 in Chapter 17 discusses how to write this function correctly. 15. [was #8]
(a) 3 (b) 0 (c) The length of the longest prefix of the string s that consists entirely of characters from the string t. Or, equivalently, the position of the first character in s that is not also in t. 16. [was #16]
int count_spaces(const char *s) {
int count = 0;
while (*s)
if (*s++ == ' ') count++; return count; }
Answers to Selected Programming Projects 1. [was #14] #include
相关推荐: