getchar函数
1. 使用getchar读入连续字符并回显
getchar函数返回的是一个int型的数据,用来保存输入字符的ASCII值。
#include <stdio.h>
int main()
{
char c;
while((c = getchar()) != '\n')
{
printf("%c", c);
}
printf("\n");
return 0;
}
2.使用getchar()函数来动态保存一个字符串
需求:当从键盘输入的字符串长度大于默认申请的内存时,自动从新申请一个更大的空间来保存字符串。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char *GetString();
int main()
{
char *p = GetString();
return 0;
}
char *GetString()
{
int str_size = 5;
char *old_str = (char*)malloc(str_size);
char *p_old = old_str;
char *new_str = NULL;
int count = 0;
char char_temp;
while((char_temp = getchar()) != '\n')
{
*old_str = char_temp;
old_str++;
count++;
if(count + 1 == str_size)
{
*old_str = '\0';
str_size += 5;
new_str = (char*)malloc(str_size);
strcpy_s(new_str, str_size, p_old);
old_str = new_str + count;
free(p_old);
p_old = new_str;
}
}
*old_str = '\0';
return p_old;
}
3. ++i与i++的区别
例1:int a=0; int b=1; a++ && b++; a++ || b++;求执行完语句后a,b的值各为多少?
本题涉及短路求值:
当执行 a++ && b++ 时,a++ 表达式返回0,故 && 左式为假,不再执行右式;当执行 a++ || b++ 时,a++ 表达式返回1(因为上一条语句执行了a++后,本次语句执行时 a 为1,故本次 a++ 返回1),则又不执行右式。
故最终的结果为 a=2, b=1。
例2:int a = 1; printf("%d", ++a); 的输出为多少?
答案为2。