c语言学习笔记 20210301

ctype.h字符函数和字符串

#include <stdio.h>
#include <ctype.h>
#define LIMIT 81
void ToUpper(char*);
int PunctCount(const char*);

int main(void)
{
	char line[LIMIT];
	char* find;

	puts("Please enter a line:");
	fgets(line, LIMIT, stdin);
	find = strchr(line, '\n');
	if (find)
		*find = '0';
	ToUpper(line);
	puts(line);
	printf("That line has %d punctuation characters.\n", PunctCount(line));
	return 0;
}

void ToUpper(char* str)
{
	while (*str)
	{
		*str = toupper(*str);
		str++;
	}
}

int PunctCount(const char* str)
{
	int ct = 0;
	while (*str)
	{
		if (ispunct(*str))
			ct++;
		str++;
	}
	return ct;
}

strchr()函数查找换行符首次出现的位置, 赋予find, 将fgets()中输入的换行符转换为空字符’\0’;toupper()函数将字符转换为大写,通过ispunct()的返回值来确定标点符号。
在一些比较旧的C的toupper / tolower()不会自动检查大小写, 故通常会这么写:

if (islower(*str))
	* str = toupper(*str);

命令行参数(command-line argument)

在linux下, 假设有个可执行程序为test, 则运行该程序的命令行(command line)为:

         $ ./test

命令行为同一行的附加行

$ ./test deep dark fantasy

默认的C编译器允许main()没有参数或者有两个参数, 第一个参数为命令行中字符串数量即参数计数(argument count)argc

//repeat.c
#include <stdio.h>
int main(int argc, char* argv[])
{
	int count;

	printf("The command line has %d arguments:\n", argc - 1);
	for (count = 1; count < argc; count++)
		printf("%d: %d\n", count, argv[count]);
	printf("\n");
	return 0;
}

如上示例中, 若通过命令行启动程序:

C>repeat Resistance is futile
The command line has 3 arguments:
1: Resistant
2: is 
3: futile

包括命令名在内共四个字符串, 后三个供repeat使用, 将每个字符串的地址存储在指针数组中。 该数组的地址储存在main()的第二个参数中, 该指向指针的指针称为argv(参数值[argument value])。若系统允许, 程序本身的名字被赋予argv[0]。
可以用双引号将多个单词括起来形成同一个参数, 如

$ ./repeat "I am hungry" now
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值