7.4 格式化输入——scanf函数
#include <stdio.h>
int main()
{
double sum;
float v;
sum = 0;
while (scanf_s("%1f", &v) == 1)
{
printf("\t%.2F\n", sum += v);
}
return 0;
}
#include <stdio.h>
int main()
{
int day, year; char monthname[20];
while (scanf_s("%d %s %d", &day, monthname, (unsigned)sizeof(monthname), &year) == 3)
{
printf("%d %s %d", day, monthname, year);
}
return 0;
}
#include <stdio.h>
#define MAXLINE 100
int getline(char line[], int lim);
int main()
{
int day, month,year;
char monthname[20];
char line[MAXLINE];
while (getline(line, sizeof(line)) > 0)
{
if (sscanf_s(line,"%d %s %d", &day, monthname, (int)sizeof(monthname),&year) == 3)
{
printf("valid: %s\n", line);
}
else if (sscanf_s(line,"%d/%d/%d", &month, &day, &year) == 3)
{
printf("valid: %s\n", line);
}
else
{
printf("invalid: %s\n", line);
}
}
return 0;
}
int getline(char x[], int limit)
{
int c, i;
c = 0;
i = 0;
for (i = 0; i < limit - 1 && (c = getchar()) != EOF && c != '\n'; ++i)
{
x[i] = c;
}
if (c == '\n')
{
x[i] = c; //x[i++] = c;
i++;
}
x[i] = '\0';
return i;
}
7.5 文件访问
在windows平台下,运行命令行参数的步骤参考
5.10 命令行参数
#include <stdio.h>
typedef int errno_t;
errno_t err;
int main(int argc, char* argv[])
{
FILE* fp;
void filecopy(FILE*, FILE*);
if (argc == 1)
{
filecopy(stdin, stdout);
}
else
{
while (--argc > 0)
{
if ((err = fopen_s(&fp, *++argv, "r")) != 0)
{
printf("cat : cant't open %s\n", *argv);
return 1;
}
else
{
filecopy(fp, stdout);
fclose(fp);
}
}
}
return 0;
}
void filecopy(FILE* ifp, FILE* ofp)
{
int c;
while ((c = getc(ifp)) != EOF)
{
putc(c, ofp);
}
}
7.6 错误处理——stderr和exit
#include <stdio.h>
#include <stdlib.h>
typedef int errno_t;
errno_t err;
int main(int argc, char* argv[])
{
FILE* fp;
void filecopy(FILE*, FILE*);
char* prog = argv[0];
if (argc == 1)
{
filecopy(stdin, stdout);
}
else
{
while (--argc > 0)
{
if ((err = fopen_s(&fp, *++argv, "r")) != 0)
{
fprintf(stderr,"%s : cant't open %s\n",prog, *argv);
exit(1);
}
else
{
filecopy(fp, stdout);
fclose(fp);
}
}
}
if (ferror(stdout))
{
fprintf(stderr, "%s : error writing stdout\n", prog);
exit(2);
}
exit(0);
}
void filecopy(FILE* ifp, FILE* ofp)
{
int c;
while ((c = getc(ifp)) != EOF)
{
putc(c, ofp);
}
}
7.7 行输入和行输出
#include <stdio.h>
#include <string.h>
char* fgets(char* s, int n, FILE* iop)
{
register int c;
register char* cs;
cs = s;
while (--n > 0 && (c = getc(iop)) != EOF)
{
if ((*cs++ = c) == '\n')
break;
}
*cs = '\0';
return (c == EOF && cs == s) ? NULL : s;
}
int fputs(char* s, FILE* iop)
{
int c;
while (c = *s++)
{
putc(c, iop);
}
return ferror(iop) ? EOF : 1;
}
/* getline函数的另外一个版本:用fgets函数实现
读入一个输入行,并返回其长度 */
int getline(char* line, int max)
{
if (fgets(line, max, stdin) == NULL)
{
return 0;
}
else
return strlen(line);
}