#include <stdio.h>
#include <string.h>
#define M1 "How are ya, sweetie? "
char M2[40] = "Beat the clock.";
char * M3 = "chat";
int main()
{
char words[80];
printf(M1); //How are ya, sweetie? How are ya, sweetie?
puts(M1);
puts(M2); //Beat the clock.
puts(M2 + 1); //eat the clock.
strcpy(words, M2); //words == "Beat the clock."
strcat(words, "Win a toy.");//words == "Beat the clock.Win a toy."
puts(words); //Beat the clock.Win a toy.
words[4] = '\0';
puts(words); //Beat
while (*M3)
puts(M3++); //chat
puts(--M3); //hat
puts(--M3); //at
M3 = M1; //t
puts(M3); //t
return 0; //at
} //How are ya, sweetie?
要点:while循环中puts是输出指针的字符字符串
#include <stdio.h>
#include <string.h>
#define M1 "How are ya, sweetie? "
char M2[40] = "Beat the clock.";
char * M3 = "chat";
int main()
{
char str1 [] = "gawsie";
char str2 [] = "bletonism";
char *ps;
int i = 0;
for (ps = str1; *ps != '\0'; ps++)//ps == "gawsie"
{
if (*ps == 'a' || *ps == 'e')
putchar(*ps);
else
(*ps)--;
putchar(*ps); //faavrhee
}
putchar('\n');
while (str2[i] != '\0')
{
printf("%c", i % 3 ? str2[i] : '*');//*le*on*sm
++i;
}
return 0;
}
复习条件运算符与取余符号%:
条件运算符当?前取得的值判断为真时,结果为:前的值,当?前取判断的值为假时,结果为:后的值
取余符号的几个例子:
#include <stdio.h>
int main(void)
{
printf("%d", 0 % 3);//结果为0
printf("%d", 1 % 3);//结果为1
printf("%d", 2 % 3);//结果为2
return 0;
}
改写《C primer plus》中的s_gets()函数,用指针表示法代替数组表示法便可减少一个变量i
原s_gets函数
char * s_gets(char * st, int n)
{
char * ret_val;
int i = 0;
ret_val = fgets(st, n, stdin);//fgets函数把换行符放在字符串的末尾
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;
}
改写之后
char * s_gets(char * st, int n)
{
char * ret_val;
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;
}
与答案给出的解法相同
用strchr()函数代替其中的while循环来查找换行符
char * s_gets(char * st, int n)
{
char * ret_val;
char * find;
int i = 0;
ret_val = fgets(st, n, stdin);
if (ret_val)
{
find = strchr(st, '\n')
if (find)
*find = '\0'
else
while (getchar() != '\n')
continue;
}
return ret_val;
}