2.编写一个程序,从标准输入读取几行输入。每行输入都要打印在标准输出上,前面要加上行号。在编写这个程序时要试图让程序能够处理的输入行的长度没有限制。
#include<stdlib.h>
#include<stdio.h>
int main()
{
int ch;
int line = 0;
int check = 1;
while((ch = getchar()) != EOF)
{
if(check == 1)
{
line += 1;
printf("%d", line);
check = 0;
}
putchar(ch);
if(ch == '\n')
check = 1;
}
system("pause");
return 0;
}
3.编写一个程序,从标准输入读取一些字符,并把它们写到标准输出上。它同时应该计算checksum值,并写在字符的后面。
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char checksum = -1;
int ch;
while( (ch = getchar()) != EOF && ch != '\n')
{
putchar(ch);
checksum += ch;
}
printf("\n%d\n",checksum);
system("pause");
return 0;
}
4.编写一个程序,一行行地读取输入行,直至到达文件尾。算出每行输入行的长度,然后把最长的那行打印出来。为了简单起见,你可以假定所有的输出行均不超过1000个字符。
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MAX 10000
int main()
{
int length = 0;
char longest[MAX];
char input[MAX];
while(gets(input) != NULL)
{
int len = strlen(input);
if(len > MAX)
{
printf("input longer than MAX");
return -1;
}
if(len < MAX)
{
length = len;
strcpy(longest, input);
}
}
if(length > 0)
printf("the longest string %s length is %d\n",longest,length);
system("pause");
return 0;
}
- rearrange程序中的下列语句
if(columns[col] >= len …)
break;
当字符的列范围超出输入行的末尾时就停止复制。这条语句只有当列范围以递增顺序出现时才是正确的,但事实上并不一定如此。请修改这条语句,即使列范围不是按顺便读取时也能正确完成任务。
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)
if(output_col >= MAX_INPUT - 1)
break;
if(columns[col] >= len)
continue;
if(nchars <= 1)
{
printf("columns error, begin small than end!\n");
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';
}
6.修改rearrange程序,去除输入中列标号的个数必须是偶数的限制。如果读入的列标号为奇数个,函数就会把最后一个列范围设置为最后一个列标号所指定的列到行尾之间的范围。从最后一个列标号直至行尾的所有字符都将被复制到输出字符串。
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;
/*如果输入行或输出行数组已满,就结束任务*/
//if(columns[col] >= len || output_col == MAX_INPUT - 1)
if(output_col >= MAX_INPUT - 1)
break;
if(columns[col] >= len)
continue;
if(col+1 >= n_columns)
nchars = columns[col+1] - columns[col] + 1;
if(nchars <= 1)
{
printf("columns error, begin small than end!\n");
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';
}