顯示具有 程式範例 標籤的文章。 顯示所有文章
顯示具有 程式範例 標籤的文章。 顯示所有文章

2012年2月23日 星期四

C/C++筆記-將程式碼去掉註解

題目:將C/C++程式碼註解去掉,並輸出結果
作法:循序搜尋程式碼註解起始標記,便紀錄位址,
          再找到註解結尾標記,然後刪除註解中所有字元
提示:單引號和雙引號內的註解符號並不是註解

線上程式碼:removeComment
下載程式碼:removeComment.rar
##ReadMore##
OS:很久沒寫程式了,從一些簡單邏輯開始練起

2012年2月15日 星期三

C/C++筆記-判斷一數是否為2的次方數值

// X值與X-1值做AND運算,若傳回0,則為2次方數值
int X;
cin >> X;
cout << !(X&(X-1)) << endl; 

2012年2月14日 星期二

C/C++筆記-兩數交換,不使用中間變數

兩數值交換,不使用中間變數的高效寫法

   1:      int a=2,b=3;
   2:      a=a^b;
   3:      b=a^b;
   4:      a=a^b;
   5:      cout << a << b << endl; // a=3,b=2

##ShowAll##

2009年9月12日 星期六

C/C++筆記-檔案內字串搜尋程式碼

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define fn "textfile.txt"

int search(FILE*,char *);
int main(void)
{
  int last=0;
  char buf[80];
  FILE *fp;
  fp = fopen(fn,"r+");
  scanf("%s",buf); //輸入要找的字串
  while(1)
  {
    int line = search(fp,buf);
    if(line)
      printf("%s found in line %d.\n",buf,line+last);
    else
      break;
    last += line; //更新目前計算的行數
  }
  fclose(fp);
  system("pause");
  return 0;
}

int search(FILE *fp,char *s)
{
  int i,j=0;
  char buf[80];
  for(i=1 ; fgets(buf,80,fp) != NULL ; i++)
    if(strstr(buf,s) != NULL) //從buf字串中找s字串
      return i;
  return 0;
}
##ShowAll##

2009年9月11日 星期五

C/C++筆記-顯示檔案內容並計算字數程式碼

#include <stdio.h>
#include <stdlib.h>
int main(void)
{
  int i;
  File *fp;
  char f[10],buf[80]; //檔名不超過10個字母,一行不超過80字元
  scanf(%s,f);
  if((fp = fopen(f,"r")) == NULL) exit(1);
  while(fgets(buf,80,fp)) != NULL)
    fputs(buf,stdout); //將檔案一行行輸出
  printf("\n");
  rewind(fp); //將串流fp指回檔案開頭
  for(i=0;;i++)
    if(fscanf(fp,"%s",buf) == EOF)
      break;
  fclose(fp);
  system("pause");
  return 0;
}
##ShowAll##

2009年8月15日 星期六

C/C++筆記-檔案複製程式碼

#include <stdio.h>
#include <stdlib.h>
int main(void)
{
  char ch;
  char src[] = "file1.txt";
  char dst[] = "file2.txt";
  File *from,*to;
  if((from = fopen(src,"rb")) == NULL) exit(1);
  if((to = fopen(dst,"wb")) == NULL) exit(1);
  while(fread(&ch,sizeof(ch),1,from) != 0)
    fwrite(&ch,sizeof(ch),1,to);
  fclose(from);
  fclose(to);
  system("pause");
  return 0;
}
##ShowAll##
/