C語言:EOF用法、儲存下標
阿新 • • 發佈:2018-12-21
#include<stdio.h> //列印標準輸出行,加上行號 void Print() { int line = 1; int ch; int flg = 1;//1代表在行的開始 0代表不在行的開始 while((ch = getchar()) != EOF)//EOF:測試檔案尾 { if(flg == 1) { if(ch == 'q' || ch == 'Q') {return;}//遇q結尾 printf("%d: ",line);//列印行 line++; flg = 0; } if(ch == '\n') { flg = 1; } putchar(ch);//輸出行值 } } //從標準輸入中讀入字元,並計算checksum的值 int CheckSum() { int ch; signed char sum = -1; while((ch = getchar()) != '\n') { sum += ch; printf("%c",ch); } sum += '\n'; //Hello world!102 return sum; } //一個有序陣列,兩個值相加,和為key 把這兩個下標儲存下來 void SumK(int *arr,int key,int *num1,int *num2,int len) { int low = 0; int high = len-1; int sum = 0; while(low < high) { sum = arr[low] +arr[high] ; if(sum == key) { *num1 = low; *num2 = high; break; } else if(sum < key)//15 < 20 { low++; } else { high--; } } } int main() { int arr[] = {4,6,8,9,10,11,13,23}; int len = sizeof(arr)/sizeof(arr[0]); int index1 = -1; int index2 = -1; SumK(arr,21,&index1,&index2,len); printf("%d,%d\n",index1,index2); /*Print(); printf("%d\n",CheckSum());*/ getchar(); return 0; }