流和緩沖區的理解及標準輸入的解決方法
- 發布于:2023-11-10
- 共 192 人圍觀
1、執行以下程序:
代碼:
/*****************************************************
Name: copy_bar.c
Copyright: kernelxu
Author: kernelxu
Date: 2005-08-02 11:20
Description: show the progress bar while doing copy
****************************************************/
#include <stdio.h>
int main(void)
{
char c = '\0';
int i = 0;
long j = 0L;
putchar('\n');
puts("Copy?(y/n): \n");
for (; (c = getchar()) == 'y' || c == 'Y'; )
{
printf("Coping......");
for (i = 0; i <= 100; i++)
{
printf("%%%3d", i);
printf("\b\b\b\b");
j = 0L;
while (j < 20000000)
{
j++; /*delay相當于linux中sleep(n)*/
}
}
puts("\nFinished!\n");
puts("Copy?(y/n): \n");
}
system("pause");
return 0;
}
該程序實現一項簡單的狀態條顯示功能(當然只是玩玩而已),但是它不能循環進行下去,程序執行一次循環就跳出了。
2、
代碼:
/*****************************************************
Name: login_example.c
Copyright: kernelxu
Author: kernelxu
Date: 2005-08-02 14:17
Description: taking login for example to say sth about I/O buffer
*****************************************************/
#include <stdio.h>
#include <string.h>
#define NAME_MAX 10
#define USER_NAME "kernelxu\0"
#define PASS_WORD 123456
int main(void)
{
char userName[NAME_MAX] = {'\0'};
unsigned long passWord = 0UL;
for(; ; )
{
printf("Login:");
gets (userName);
printf("Password:");
scanf("%ld", &passWord);
if(passWord != PASS_WORD || strcmp(userName, USER_NAME) != 0)
{
printf("Login Incorrect!\n");
continue;
}
break;
}
printf("[%s@localhost ~]$", userName);
getch();
return 0;
}
該程序只要輸入的用戶名超過NAME_MAX-1值或者password輸入的不是正整數,就無法登錄了。
以上兩例程序之所以存在很大的問題,主要是在處理標準輸入緩沖及選擇輸入函數上不夠慎重。本文先總結一下流(stream)、緩沖區(buffer)的概念,然后重點說一下這類問題的解決之道。
標簽: