目录
使用教材:C primer plus
1.1 Visual Studio 2019使用
1.2 快速上手(《C与指针》)
#pragma warning(disable:4996)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_COLS 20 /*所能处理的最大列号*/
#define MAX_INPUT 1000 /*每个输入行的最大长度*/
int read_column_numbers(int columns[], int max);
void rearrange(char* output, char const* input,
int n_columns, int const columns[]);
int main(void)
{
int n_clomns; /*进行处理的列标号*/
int columns[MAX_COLS]; /*需要处理的列数*/
char input[MAX_INPUT]; /*容纳输入行的数组*/
char output[MAX_INPUT]; /*容纳输出行的数组*/
/*
**读取该串列表号
*/
n_clomns = read_column_numbers(columns, MAX_COLS);
while (gets_s(input,1000) != NULL) {
printf("Original input : %s\n", input);
rearrange(output, input, n_clomns, columns);
printf("Reattangeed line: %s\n", output);
}
return EXIT_SUCCESS;
}
/*
**读取列表号,如果超出规定则不予理会
*/
int read_column_numbers(int columns[], int max)
{
int num = 0;
int ch;
/*
**读取列表号,如果超出规定范围则不予理会
*/
while (num < max && scanf("%d", &columns[num]) == 1
&& columns[num] >= 0)
num += 1;
/*
**确认已经读取的标号为偶数个,因为他们是以对的形式出现的
*/
if(num % 2 != 0){
puts("Last colum number is not paired.");
exit(EXIT_FAILURE);
}
/*
**丢弃该行中包含最后一个数字的那部分内容
*/
while ((ch = getchar()) != EOF && ch != '\n')
;
return num;
}
/*
**处理输入行,将指定列的字符连接在一起,输出行以NUL结尾
*/
void rearrange(char* output, char const* input,
int n_columns, int const columns[])
{
int col; /*columns数组的下标*/
int output_col; /*输出行计数器*/
int len; /*输入行的长度*/
len = strlen(input);
output_col = 0;
/*
**处理每队列标号
**/
for (col = 0; col < n_columns; col += 2) {
int nchars = columns[col + 1] - columns[col] + 1;
/*
**如果输入行结束输出行数组已满,就结束任务
*/
if (columns[col] >= len || output_col == MAX_INPUT - 1)
break;
/*
**如果输出行数数据空间不够,只复制可以容纳的数据
*/
if (output_col + nchars > MAX_INPUT - 1)
nchars = MAX_INPUT - output_col - 1;
/*
**复制相关数据
*/
strncpy(output + output_col, input + columns[col], nchars);
output_col += nchars;
}
output[output_col] = '\0';
}
error C4996: 'scanf': This function or variable may be unsafe.
在.c文件中的头部加入#pragma warning(disable:4996)
warning C4013: “gets”未定义;假设外部返回 int
gets_s(字符数组名,参数) 参数:参数为存储字符串的空间长度!
编译运行程序:
1.3 教材复习题
- 对编程而言,可移植性意味着什么?
完美的可移值程序是其源代码无需修改就能在不同计算机系统中成功编译程序。
- 解释源代码文件、目标代码文件和可执行文件有什么区别?
源代码文件包含程序员使用的任何编程语言编写的代码。目标代码文件包含机器语言代码,他不必是完整的程序代码。可执行文件包含组成可执行程序的完整机器语言代码。
- 编程的七个主要步骤是什么?
- 定义程序目标
- 设计程序
- 编写代码
- 编译
- 运行程序
- 测试和调试程序
- 维护和修改代码
- 编译器的任务是什么?
编译器把源代码(如:用C语言编写的代码)翻译成等价的机器代码(也叫目标代码)。
- 链接器的任务是什么?
链接器是把编译器编译好的源代码以及库代码和启动代码组合起来,生成一个可执行程序。