c程序设计语言 by K&R(一)一些c语言基础知识

出自《c程序设计语言》 by K&R:
一、导言
二、类型、运算符与表达式
三、控制流

1. 字符输入与输出

getchar()putchar(),输入一个字符、输出一个字符

#include <stdio.h>
#include <stdlib.h>

int main(void) {
	int c = getchar();
	while(c != EOF){
		putchar(c);
               
		c = getchar();
	}
	return 0;
}

更简洁的形式

#include <stdio.h>
#include <stdlib.h>

int main(void) {
	int c;
	while((c = getchar()) != EOF){
		putchar(c);
	}
	return 0;
}

输入与输出

dfadkfl
dfadkfl
fopawfjkw
fopawfjkw

2. 字符数组

实现getline函数

3.定义和声明的区别

“定义”表示创建变量或分配存储单元,而“声明”指的是说明变量的性质,并不分配存储单元。

4. ~与!

按位取反 和 逻辑非

#include <stdio.h>
#include <stdlib.h>

int main(void) {

	int a = 0;
	int b = !a;
	int c = ~a;
	printf("%d %d\n", b, c);
	return 0;
}

输出:

1 -1

5.整数与字符串的相互转换

  1. atoi (alphanumeric to integer)

int atoi(const char *nptr);//字符串转整数函数,nptr: 要转换的字符串

  1. atol (alphanumeric to long integer)

long int atol(const char *str)

  1. itoa (integer to alphanumeric)

char* itoa(int value,char*string,int radix);//value: 要转换的整数,string: 转换后的字符串,radix: 转换进制数,如2,8,10,16 进制等。

  1. 利用 sprintf() 函数和 sscanf() 函数

ANSI C 规范定义了 stof()、atoi()、atol()、strtod()、strtol()、strtoul() 共6个可以将字符串转换为数字的函数

6. 宏定义: 将替换文本在直接插入到代码

  1. #define的一些注意事项
  • 注意打括号

如果有以下定义:

#define square(x) x*x

那么square(z+1) 将会是 z + 1 * z + 1

正确的定义应为

#define square(x) ((x)*(x))

  • max(a++, b++) 中的a、b都会执行两次自增操作

#define max(A,B) ((A) > (b) ? (A) : (b))

  1. #undef 取消名字的宏定义

  2. ## 用于连接实际参数

#define paste (front, back) front##back

paste(name, 1)将建立记号name1

  1. 条件包含
  • #if:

对其中的表达式求值,如果该表达式不为0,则包含其后的各行,直到遇到#endif、#elif、#else为止

  • defined(名字):

如果该名字已定义,则其值为;否则为0。

  • #ifdef 和 #ifndef 用来测试某个名字是否定义

#ifndef HDR

相当于

#if !defined(HDR)

原文地址:https://www.cnblogs.com/qiangz/p/15775222.html