Việt - Nhật 's class
Bạn có muốn phản ứng với tin nhắn này? Vui lòng đăng ký diễn đàn trong một vài cú nhấp chuột hoặc đăng nhập để tiếp tục.
Latest topics
» Oblivion - Phim Club
Week 12 (Full) I_icon_minitime06/02/14, 11:10 am by sshin_conan

» các bạn/anh/chị cho hỏi đề thi giải tích 1
Week 12 (Full) I_icon_minitime03/05/13, 09:47 pm by ictk56

» Đề nghị sát nhập 2 diễn đàn
Week 12 (Full) I_icon_minitime18/02/12, 11:01 am by ngoanhtuan_hn

» Hội nghị sinh viên Việt Nam Nhật Bản tuyển thành viên
Week 12 (Full) I_icon_minitime17/02/12, 11:43 pm by michiosatoo

» mình có câu này, mong các bạn dịch giúp!!!
Week 12 (Full) I_icon_minitime16/11/11, 06:17 pm by asakurayo

» nho forum chut
Week 12 (Full) I_icon_minitime15/11/11, 11:29 am by asakurayo

» CS 1.6 MAP MAKER
Week 12 (Full) I_icon_minitime15/11/11, 07:55 am by asakurayo

» ubuntu-win
Week 12 (Full) I_icon_minitime12/10/11, 05:46 pm by darklord226

» diễn đàn hedspi k56
Week 12 (Full) I_icon_minitime11/10/11, 09:41 pm by lakazai


Week 12 (Full)

5 posters

Go down

Week 12 (Full) Empty Week 12 (Full)

Bài gửi by haidang001 08/05/11, 12:48 pm

Phong thanh thấy thầy bảo tuần sau lớp "bị nghỉ", có thể bài tập tuần này "đông đúc" là do dồn của 2 tuần.
Koltec tiếp tục series với 5 bài của "week12".

Phần 1: Đề bài.

Bài 1: encrypt (mã hóa).
Code:

    Phuong phap ma hoa co dien cac van ban duoc thuc hien nhu sau:
          a) Dich ky tu sang k buoc trong bang chu cai, va xoay vong tron. Vi du: a -> c, b -> d, z -> b. Viec giai ma duoc thuc hien nguoc lai.
    Viet ham ma hoa va giai ma mot xau ky tu voi gia tri buoc dich chuyen tuy bien o dang tham so.
    Su dung ham tren de ma hoa mot doan van ban nhap tu ban phim sau do giai ma.

Bài 2: firstname (tên)
Code:

    Write a program asks the user to enter his or her first and last names, separated by a space. Then print out the first name.
    The program should use function cut off the last name from parameter string.

Bài 3: strend (xâu cuối)
Code:

    Write the function strend(s, t), which returns 1 if the string t occurs at the end of the string s, and zero otherwise.

Bài 4: strim (hàm cắt . . . ,sờ trym)
Code:

    Viet ham trimright(char a[]) loai bo tat ca cac ky tu trang lien nhau o cuoi xau a.
    Viet ham trimleft(char a[]) loai bo tat ca cac ky tu trang lien nhau o dau xau a.
    Viet ham trimmiddle(char a[]) dua tat ca cac dau trang lien nhau o giua xau ve 1.
    Test voi xau: "  Cong  hoa xa    hoi CNVN.  "

Bài 5: date (ngày tháng)
a) Create a tructure named Date for storing date concerining variables. Each date has a day, a month and a year.
b) Write a function for the input of variable of this type. Remember to check the validation of data.
c) Write a function to datecmp to compare two date which return
-1 if the first date (parameter) is before the second
0 if two date are identical.
1 if the first date (parameter) is after the second
d) Write a program asking user to for two date and print out the results of the comparision.

For example: 2.10.1997 is after 23.8.1997

Phần 2: Tip
Bài 1: encrypt (mã hóa).
1. Lưu ý phần kí tự không phải là chữ cái, chẳng hạn ' ', '@', '!'. . Cần đưa ra quy tắc chung cho việc mã hóa các kí tự này. Giữ nguyên chẳng hạn.
2. Chữ hoa và chữ thường là khác nhau, tránh nhầm lần khi coding.
Code:

if ('a' == 'A')
  printf("Koltec sai nhăn răng rồi! Ha ha:))");
else
  printf("Anh Koltec thông minh, đẹp trai, nhà giàu! S_have fun! :)");
3. Đây là encrypt của Koltec
Code:

char *encrypt(char a[], int n)
{
  char *x;
  for(x = a; *x != '\0'; x++)
    if (lowchar(*x) == 1)
      *x = (n + *x - 'a') % ('z' - 'a' + 1) + 'a';
    else
      if (upchar(*x) == 1)
    *x = (n + *x - 'A') % ('Z' - 'A' + 1) + 'A';
      else
    if (numchar(*x) == 1)
      *x = (n + *x - '0') % ('9' - '0' + 1) + '0';
  return a;
}

Decrypt (giải mã) --> tương tự công thức trong encrypt.

Bài 2: firstname (tên)
Chú ý phần kí tự ' ' (spacebar) ở đầu xâu.
Code:

  while (*s == ' ')
    s++;

Bài 3: strend (xâu cuối)
Đặc biệt chú ý: trường hợp xâu rỗng

Bài 4: strim (hàm cắt . . . ,sờ trym)
Đặc biệt chú ý là không có gì đặc biệt chú ý cả.

Bài 5: date (ngày tháng)
1. Bài yêu cầu dùng cấu trúc dữ liệu bản ghi "struct", và định nghĩa kiểu dữ liệu mới "typedef"
Code:

typedef struct date
{
  int date, month, year;
} date_t;
2. Cần kiểm tra dữ liệu đầu vào:
3. Sử dụng đến hàm chuyển đổi từ xâu sang số:
Code:

  char istr = "12";
  int x = atoi(istr);
  printf("%d\nS_have fun! :)\n", x);
4. So sánh thời điểm của 2 ngày được nhập:thứ tự năm --> tháng --> ngày.
Code:

int datecmp(date_t x, date_t y)
{
  if (x.year != y.year)
    return (x.year < y.year) ? -1 : 1;
  if (x.month != y.month)
    return (x.month < y.month) ? -1 : 1;
  if (x.date != y.date)
    return (x.date < y.date) ? -1 : 1;
  return 0;
}

Phần 3: Solution.
vẫn lại lưu ý cũ: Koltec の code hoàn toàn mang tính chất tham khảo, chưa dám chắc đúng hết. Có gì ae góp ý hộ.

Trên trang web http://www.haidang001.tk, có đầy đủ code từ week1. Ae lên tham khảo.

Bài 1: encrypt (mã hóa).
Code:

/*Copyright (c) haidang001 (tm) (@yahoo.com)*/
/*2011 Allright reserved*/

/*    Phuong phap ma hoa co dien cac van ban duoc thuc hien nhu sau:
          a) Dich ky tu sang k buoc trong bang chu cai, va xoay vong tron. Vi du: a -> c, b -> d, z -> b. Viec giai ma duoc thuc hien nguoc lai.
    Viet ham ma hoa va giai ma mot xau ky tu voi gia tri buoc dich chuyen tuy bien o dang tham so.
    Su dung ham tren de ma hoa mot doan van ban nhap tu ban phim sau do giai ma.*/

#include
#define maxsize 10000

void enter(char [], int *);
int check(char []), lowchar(char), upchar(char), numchar(char);
char *encrypt(char [], int ), *decrypt(char [], int);

main()
{
  int n;
  char a[maxsize];
  enter(a, &n);
 
  printf("Text after encrypted:\n");
  printf("%s\n", encrypt(a, n));

  printf("Encrypted text after decrypted:\n");
  printf("%s\n", decrypt(a, n));
 
  printf("\nS_have fun! :)\n");
  return 0;
}

char *decrypt(char a[], int n)
{
  char *x;
  for(x = a; *x != '\0'; x++)
    if (lowchar(*x) == 1)
      *x = ((-n + *x - 'a') % 26 + 26) % 26 + 'a';
    else
      if (upchar(*x) == 1)
    *x = ((-n + *x - 'A') % 26 + 26) % 26 + 'A';
      else
    if (numchar(*x) == 1)
      *x = ((-n + *x - '0') % 10 + 10) % 10 + '0';
  return a;
}

char *encrypt(char a[], int n)
{
  char *x;
  for(x = a; *x != '\0'; x++)
    if (lowchar(*x) == 1)
      *x = (n + *x - 'a') % ('z' - 'a' + 1) + 'a';
    else
      if (upchar(*x) == 1)
    *x = (n + *x - 'A') % ('Z' - 'A' + 1) + 'A';
      else
    if (numchar(*x) == 1)
      *x = (n + *x - '0') % ('9' - '0' + 1) + '0';
  return a;
}

int lowchar(char x)
{
  if ((x >= 'a') && (x <= 'z'))
    return 1;
  return 0;
}

int upchar(char x)
{
  if ((x >= 'A') && (x <= 'Z'))
    return 1;
  return 0;
}

int numchar(char x)
{
  if ((x >= '0') && (x <= '9'))
    return 1;
  return 0;
}

int check(char a[])
{
  char *x;
  for(x = a; (*x) != '\0'; x++)
    if ((*x != ' ') && ((lowchar(*x) == 0) && (upchar(*x) == 0) && (numchar(*x) == 0)))
      return 0;
  return 1;
}

void enter(char a[], int *n)
{
  do
    {
      printf("Enter a line of plain text('a'-'z', '0'-'9', 'A'-'Z', ' '):\n");
      gets(a);
      if (check(a) == 0)
    printf("Invalid input!\n");
      else
    break;
    }
  while (1);
 
  printf("Enter number of skips: ");
  scanf("%d", n);
  getchar();
 
  printf("\n");
  return;
}

//S_have fun! :)

Bài 2: firstname (tên)
Code:

/*Copyright (c) haidang001 (tm) (@yahoo.com)*/
/*2011 Allright reserved*/

/*    Write a program asks the user to enter his or her first and last names, separated by a space. Then print out the first name.
    The program should use function cut off the last name from parameter string.*/

#include
#define maxsize 1000

char *firstname(char []);

main()
{
  char a[maxsize];
  printf("Enter your name (at which first and last names separated by at least one space): ");
  gets(a);
  printf("Your first name is %s\n", firstname(a));
 
  printf("\nS_have fun! :)\n");
  return 0;
}

char *firstname(char a[])
{
  while (*a == ' ')
    a++;
  char *x = a;
  while (*x != ' ')
    x++;
 
  *x = '\0';
  return a;
}

//S_have fun! :)

Bài 3: strend (xâu cuối)
Code:

/*Copyright (c) haidang001 (tm) (@yahoo.com)*/
/*2011 Allright reserved*/

/*    Write the function strend(s, t), which returns 1 if the string t occurs at the end of the string s, and zero otherwise.*/

#include
#define maxsize 1000

int strend(char [], char []);

main()
{
  char s[maxsize], t[maxsize];
 
  printf("Enter first string:\n");
  gets(s);
  printf("Enter second string:\n");
  gets(t);

  if (strend(s, t) == 1)
    printf("Second string occurs at the end of first string\n");
  else
    printf("Send cond string doesn't occur at the end of first string\n");

  printf("\nS_have fun! :)\n");
  return 0;
}

int strend(char s[], char t[])
{
  char *x = s, *y = t;
 
  while (*x != '\0')
    x++;
  while (*y != '\0')
    y++;

  while ((x != s) && (y != t))
    if (*(x--) != *(y--))
      return 0;
  if ((y == t) && (*x == *y))
    return 1;
  else
    return 0;
}

//S_have fun! :)

Bài 4: strim (hàm cắt . . . ,sờ trym)
Code:

/*Copyright (c) haidang001 (tm) (@yahoo.com)*/
/*2011 Allright reserved*/

/*    a) Create a tructure named Date for storing date concerining variables. Each date has a day, a month and a year.
    b) Write a function for the input of variable of this type. Remember to check the validation of data.
    c) Write a function to datecmp to compare two date which return
          -1    if the first date (parameter) is before the second
          0        if two date are identical.
          1        if the first date (parameter) is after the second
    d) Write a program asking user to for two date and print out the results of the comparision.

    For example: 2.10.1997 is after 23.8.1997*/

#include
#define maxsize 1000

typedef struct date
{
  int date, month, year;
} date_t;

date_t enter(char []);
int numchar(char), convert(char [], date_t *), length(char []), check(date_t), datecmp(date_t, date_t);
                                        void copy(char [], char [], int, int), dateprint(date_t);
const ndate[13] = {0, 31, 0, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
          // 1  2  3  4  5  6  7  8  9  10  11  12

main()
{
  date_t x, y;

  x = enter("Enter first date (dd/mm/yyyy): ");
  y = enter("Enter second date (dd/mm/yyyy): ");

  printf("\n");
  dateprint(x);
  printf(" is ");
  int t = datecmp(x, y);
  if (t == -1)
    printf("before ");
  else
    if (t == 0)
      printf("identical ");
    else
      printf("after ");
  dateprint(y);
  printf("\n");
 
  printf("\nS_have fun! :)\n");
  return 0;
}

int numchar(char x)
{
  if ((x >= '0') && (x <= '9'))
    return 1;
  return 0;
}

void refine(char a[]) //after this function, a[] remains number character only. S_have fun! :)
{
  char *x, *y;
  for(x = a, y = a; *x != '\0'; x++)
    if (numchar(*x) == 1)
      *(y++) = *x;
  *y = '\0';
  return;
}

date_t enter(char say[])
{
  date_t x;
  char a[maxsize];
 
  do
    {
      printf("%s", say);
      gets(a);
      refine(a);
    }
  while (convert(a, &x) == 0);
  return x;
}

int length(char a[])
{
  int res = 0;
  char *x;
  for(x = a; *x != '\0'; x++)
    res++;
  return res;
}

void copy(char des[], char sou[], int st, int len)//Copy \len character starting at \st from \sou[] to des[]
{
  char *x = des, *y = sou;
  while (--st > 0)
    y++;
  while (len-- > 0)
    *x++ = *y++;
  *x = '\0';
  return;
}

int check(date_t x)
{
  if ((x.month < 1) || (x.month > 12))
    return 0;
  if (x.date < 1)
    return 0;
  if (x.month == 2)
    {
      if ((x.date == 29) && (x.year % 4 == 0))
    return 1;
      if (x.date > 28)
    return 0;
    }
  else
    if (x.date > ndate[x.month])
      return 0;
  return 1;
}

int convert(char a[], date_t *x)
{
  char tmp[10];
 
  if (length(a) < 8)
    return 0;

  copy(tmp, a, 1, 2);
  (*x).date = atoi(tmp);

  copy(tmp, a, 3, 2);
  (*x).month = atoi(tmp);

  copy(tmp, a, 5, 4);
  (*x).year = atoi(tmp);
  return check(*x);
}

int datecmp(date_t x, date_t y)
{
  if (x.year != y.year)
    return (x.year < y.year) ? -1 : 1;
  if (x.month != y.month)
    return (x.month < y.month) ? -1 : 1;
  if (x.date != y.date)
    return (x.date < y.date) ? -1 : 1;
  return 0;
}

void dateprint(date_t x)
{
  printf("%02d/%02d/%04d", x.date, x.month, x.year);
  return;
}
//S_have fun! :)

Làm việc với xâu chuối, có rất nhiều tip (mẹo) hay. Nên code của Koltec có nhiều chỗ khá tắt. Ae thấy khó hiểu cứ post bài hỏi. Koltec cố gắng giải thích bằng cách dễ hiểu nhất.
S_have fun! So good
Bài 5: date (ngày tháng)
haidang001
haidang001

Tổng số bài gửi : 91
Points : 176
Join date : 25/09/2010
Age : 31

http://haidang001.tk

Về Đầu Trang Go down

Week 12 (Full) Empty Re: Week 12 (Full)

Bài gửi by huy_d_t 08/05/11, 01:20 pm

Đang định cướp bản quyển week12 thì Sáng chói đã kịp post rồi.
Code của huydt, hoàn toàn mang tính chất tham khảo lol! , nói chung là dài hơn code của chói:

hw1:
Code:
#include<stdio.h>
#include<string.h>

#define maxsize 100

void clearbuffer(void) {
  char ch;
  while ((ch = getchar()) != '\n' && ch != EOF);
}

void printmm(void) {
  printf("Press enter to return main menu...");
  getchar();
}

void init (char text[maxsize]) {
  printf("Enter a string:  \n\t");
  fflush(stdout);
  if (fgets(text, 100, stdin) != NULL) {
    char *newline = strchr(text, '\n');
    if ( newline != NULL ) {
      *newline='\0';
    }
  }
}
   
void trimLeft(char text[maxsize]) {
  int i,num=0;
  while ( text[num] == ' ' )
    num++;
  for(i=0 ; i<(strlen(text)+1) ; i++)
    text[i]=text[i+num];
}

void trimRight(char text[maxsize]) {
  int i=strlen(text)-1;
  while (text[i] == ' ') {
    i--;
  }
  text[i]='\0';
}

void trimMiddle(char text[maxsize]) {
  char text1[maxsize];
  int flag=0,i=0,j=0,start=0,end=strlen(text);
  while (text[i]==' ')
    i++;
  start=i;
  i=end;
  while (text[i]==' ')
    i--;
  end=i;
  for(i=start;i<=end;i++) {
    if (text[i]==' ') {
      if (flag==0) {
        flag=1;
        text1[j]=text[i];
        j++;//push text[i] to text1
      }
    }
    else {
      flag=0;
      text1[j]=text[i];
      j++;
    }
  }
  strcpy(text,text1);
}     
   
void main () {
  char select=0,exit=0,text[maxsize];
  printf("\nSimple string processes program \n");
  printf("    Author: Phung Nhat Huy\n");
  while (exit==0) {
    printf("\n\tMENU\n");
    printf("\t1.Input a string\n");
    printf("\t2.Discard space at begin of line\n");
    printf("\t3.Discard space at end of line\n");
    printf("\t4.Replace long space at middle of line by only 1 space\n");
    printf("\t5.Exit program\n");
    printf("Enter your choice :  ");
    select=getchar();
    clearbuffer();
    switch (select) {
    case '1': {
      init(text);
      printf("Inputed text: [%s]\n",text);
      printmm();
    }
      break;
     
    case '2': {
      trimLeft(text);
      printf("\t[%s]\n",text);
      printmm();
    }
      break;
     
    case '3' : {
      trimRight(text);
      printf("\t[%s]\n",text);
      printmm();
    }
      break;
     
    case '4': {
      trimMiddle(text);
      printf("\t[%s]\n",text);
      printmm();
    }
      break;
     
    case '5': {
      exit=1;
    }
      break;
     
    default: '5';
    }
  }
}

hw2:
Code:
// Simple encryption program using Ceasar cipher
// Author: huydt

#include<stdio.h>
#include<string.h>

#define maxsize 100

void clearbuffer(void) {
  char ch;
  while ((ch = getchar()) != '\n' && ch != EOF);
}

void printmm(void) {
  printf("Press enter to return main menu...");
  getchar();
}

void safegets(char text[maxsize]) {
  if ( fgets(text,100,stdin) != NULL) {
    char *newline=strchr(text,'\n');
    if (newline != NULL)
      *newline='\0';
  }
}
 
void encrypt(char text[maxsize],int k) {
  int i=0;
  while (text[i] != '\0') {
    if ( (text[i]>='a') && (text[i]<='z') )
      text[i]= (text[i]+k-'a')%26 + 'a';
    else if ( (text[i]>='A') && (text[i]<='Z') )
      text[i]= (text[i]+k-'A')%26 + 'A';
    else if ( (text[i]>='0') && (text[i]<='9') )
      text[i]= (text[i]+k-'0')%10 + '0';
    i++;
  }
}

void decrypt(char text[maxsize],int k) {
  int i=0;
  char tmp;
  while (text[i] != '\0') {
    if ( (text[i]>='a') && (text[i]<='z') ) {
      tmp = (text[i]-k-'a')%26 ;
      if (tmp>=0)
        text[i]= tmp + 'a';
      else
        text[i]= tmp + 1 + 'z';
    }
    else if ( (text[i]>='A') && (text[i]<='Z') ) {
      tmp = (text[i]-k-'A')%26 ;
      if (tmp>=0)
        text[i]= tmp + 'A';
      else
        text[i]= tmp + 1 + 'Z';
    }
    else if ( (text[i]>='0') && (text[i]<='9') ) {
      tmp = (text[i]-k-'0')%10 ;
      if (tmp>=0)
        text[i]= tmp + '0';
      else
        text[i]= tmp + 1 + '9';
    }
    i++;
  }
}
   
 
void main () {
  char text[maxsize];
  char select=0,exit=0;
  int k=0;

  printf("Simple encryption tool using Ceasar cypher\n");
  printf("Author: Phung Nhat Huy\n");
  while (exit == 0) {
    printf("\n\nMENU:\n");
    printf("\t1.Input a string\n");
    printf("\t2.Encrypt inputed string\n");
    printf("\t3.Decrypt encrypted string\n");
    printf("\t4.Exit program\n");
    printf("  Enter your choice:  ");
    select=getchar();
    printf("\n");
    clearbuffer();

    switch (select) {
    case '1': {
      printf("Enter a string to encrypt or decrypt:  \n\t");
      safegets(text);
      printf("Inputed string: \n\t[%s]\n",text);
      printmm();
    }
      break;
     
    case '2': {
      printf("Input shift parameter k:  ");
      scanf("%d",&k);
      printf("Source string:  \n\t[%s]\n",text);
      encrypt(text,k);
      printf("Encrypted string: \n\t[%s]\n",text);
      printmm();
    }
      break;
     
    case '3': {
      printf("Input shift parameter k:  ");
      scanf("%d",&k);
      printf("Source string:  \n\t[%s]\n",text);
      decrypt(text,k);
      printf("Decrypted string:  \n\t[%s]\n",text);
      printmm();
    }
      break;
     
    case '4':
      exit=1;
      break;
     
    default: '4';
    }
  }
}
 

---------------------------------------------------------------------------------

@Sáng chói: rảnh tay thì check giúp tôi, đây là phiên bản an toàn hơn của gets, mới tìm dc. Toán tử sizeof ko cho ra kết quả như mình muốn
Code:

#include<stdio.h>
#include<string.h>
#define maxsize 100
void init (char text[maxsize]) {
  printf("Enter a string:  \n\t");
  printf("%d  ",sizeof text);  /*tại sao sizeof text nhận gt là 8 chứ ko phải 100  */
  if (fgets(text, sizeof text, stdin) != NULL)  { 
    char *newline = strchr(text, '\n');
    if ( newline != NULL ) {
      *newline='\0';
    }
  }
}
trong khi với đoạn này thì lại ra đúng ( y hệt đoạn code trên, nhưng ko dùng function mà nhét thẳng vào main)
Code:


#include <stdio.h>
#include <string.h>
 
void main()
{
  char text[100];
  printf("size of text: %d \n",sizeof text); // kq ra đúng 100
  printf("enter some text here:  ");
  if ( fgets(text, sizeof text, stdin) != NULL )
  {
      char *newline = strchr(text, '\n'); /* search for newline character */
      if ( newline != NULL )
      {
        *newline = '\0'; /* overwrite trailing newline */
      }
  printf("\ninputed text: [%s]\n",text);
  }
}
huy_d_t
huy_d_t

Tổng số bài gửi : 112
Points : 142
Join date : 26/09/2010
Đến từ : Đại dâm tặc

Về Đầu Trang Go down

Week 12 (Full) Empty Re: Week 12 (Full)

Bài gửi by Tung_tobe 08/05/11, 11:08 pm

sao lắm bài thế nhỉ, tưởng có mỗi bài bỏ dấu cách liền nhau, bài mã hóa với cả bài 14.1 trong slide@@ chắc tại mải ngủ nên ko để ý. Từ bài point đã ko hiểu j đến bài này thì chịu rồi Sad( thi thố sao đây, ko có mạng thì thi bằng niềm đau ư ????
Tung_tobe
Tung_tobe

Tổng số bài gửi : 100
Points : 124
Join date : 27/09/2010

Về Đầu Trang Go down

Week 12 (Full) Empty Re: Week 12 (Full)

Bài gửi by huy_d_t 09/05/11, 12:14 am

save tất cả btvn, bài tập trên lớp vào usb. TIết cuối cùng trước khi thi mang vào copy vào phòng máy. Thao tác này dc coi là 'hợp pháp' Very Happy
nhớ lấy mẹo đổi passroot trên linux ( single-user mode), bấn quá thì dùng, lưu ý: thao tác này bất hợp pháp, việc phát hiện sự truy cập internet hay trao đổi dữ liệu trong mạng cục bộ là dễ dàng.
huy_d_t
huy_d_t

Tổng số bài gửi : 112
Points : 142
Join date : 26/09/2010
Đến từ : Đại dâm tặc

Về Đầu Trang Go down

Week 12 (Full) Empty Re: Week 12 (Full)

Bài gửi by haidang001 09/05/11, 01:41 am

huy_d_t đã viết:
@Sáng chói:
rảnh tay thì check giúp tôi, đây là phiên bản an toàn hơn của gets, mới
tìm dc. Toán tử sizeof ko cho ra kết quả như mình muốn
Code:

#include
#include
#define maxsize 100
void init (char text[maxsize]) {
  printf("Enter a string:  \n\t");
  printf("%d  ",sizeof text);  /*tại sao sizeof text nhận gt là 8 chứ ko phải 100  */
  if (fgets(text, sizeof text, stdin) != NULL)  { 
    char *newline = strchr(text, '\n');
    if ( newline != NULL ) {
      *newline='\0';
    }
  }
}
trong khi với đoạn này thì lại ra đúng ( y hệt đoạn code trên, nhưng ko dùng function mà nhét thẳng vào main)
Code:


#include
#include
 
void main()
{
  char text[100];
  printf("size of text: %d \n",sizeof text); // kq ra đúng 100
  printf("enter some text here:  ");
  if ( fgets(text, sizeof text, stdin) != NULL )
  {
      char *newline = strchr(text, '\n'); /* search for newline character */
      if ( newline != NULL )
      {
        *newline = '\0'; /* overwrite trailing newline */
      }
  printf("\ninputed text: [%s]\n",text);
  }
}



Tính không an toàn của gets() tương đương hàng ngàn thao tác khác trong C.

Khuyên cáo ae với kiểu đưa ra cảnh bảo theo kiểu "tùy hứng" này của gcc.


-------------------------------------
Về prob của huy.d.t

Code:


printf("%d  ",sizeof text);  /*tại sao sizeof text nhận gt là 8 chứ ko phải 100  */

Biến text được truyền vào ở dạng char*, mặc dù khai báo là char[] (đây
là nguyên tắc khi biên dịch của C & số đông các ngôn ngữ lập trình
khác).
Chính vì thế từ khóa sizeof trả về kích thước của biến char* (pointer) là 4 (bytes) So good

Code:

printf("size of text: %d \n",sizeof text); // kq ra đúng 100
Còn trong trường hợp gọi trực tiếp từ hàm main, biến text không phải là
char* nữa, mà nó nguyên si char[]. sizeof trả về kích thước mảng char[]
text So good.

--------------------------------
Muốn cho hàm init() thực hiện đúng chức năng đọc xâu, sửa thành:

Code:


              if (fgets(text, maxsize, stdin) != NULL)// ban đầu là if (fgets(text, sizeof text, stdin) != NULL)

=========================
Còn về cảnh bảo của gcc
Code:

the `gets' function is dangerous and should not be used.
đây vẫn chỉ là cảnh báo, do hàm gets() không phát hiện lỗi overflow khi người dùng nhập vào dòng text có kích thước lớn hơn kích thước khai bảo.
Giải pháp: khai báo chuỗi ban đầu với kích thước lớn.
Code:

char string[10000]; //S_have fun! :)

S_have fun! So good
haidang001
haidang001

Tổng số bài gửi : 91
Points : 176
Join date : 25/09/2010
Age : 31

http://haidang001.tk

Về Đầu Trang Go down

Week 12 (Full) Empty Re: Week 12 (Full)

Bài gửi by huy_d_t 09/05/11, 07:10 pm

cảm ơn chói đã check hộ So good
mặc dù nếu có gets() thì gcc chỉ báo warning, chương trình vẫn chạy đúng. Nhưng trên nhiều forum lập trình (tây lẫn ta) đều khuyên ko nên dùng gets, vì nếu chẳng may nhập thừa kí tự, gets() sẽ lấy các ô nhớ tiếp theo để lưu trữ kí tự dư thừa, nếu các ô đó được chương trình khác sử dụng thì sẽ gây ra lỗi. Thay cho gets, các developer khuyên nên dùng fgets(), vì nó định trước số ô nhớ để lưu trữ.
huy_d_t
huy_d_t

Tổng số bài gửi : 112
Points : 142
Join date : 26/09/2010
Đến từ : Đại dâm tặc

Về Đầu Trang Go down

Week 12 (Full) Empty Re: Week 12 (Full)

Bài gửi by myname2 12/05/11, 12:01 am

Sáng post bài 5 vào bài 4 và quên ko post code bài 4 So good)
myname2
myname2

Tổng số bài gửi : 66
Points : 90
Join date : 27/09/2010
Age : 31
Đến từ : Hà Nội

https://facebook.com/tuanhai

Về Đầu Trang Go down

Week 12 (Full) Empty Re: Week 12 (Full)

Bài gửi by asakurayo 12/05/11, 07:07 am

cái bài dd/mm/yyyy của sáng nhập vào kiểu gì vậy/sao tớ nhập không được nè;
[Thom@Thom Documents]$ ./a.out
Enter first date (dd/mm/yyyy): 12
Enter first date (dd/mm/yyyy): 4
Enter first date (dd/mm/yyyy): 1992
Enter first date (dd/mm/yyyy): 12/4/1992
Enter first date (dd/mm/yyyy): 12/4/92
Enter first date (dd/mm/yyyy): 1992/12/4
Enter first date (dd/mm/yyyy):
sao không thấy nó chạy nhỉ? So good
asakurayo
asakurayo

Tổng số bài gửi : 38
Points : 62
Join date : 27/12/2010
Age : 32
Đến từ : hai duong

Về Đầu Trang Go down

Week 12 (Full) Empty Re: Week 12 (Full)

Bài gửi by myname2 12/05/11, 09:29 am

Phai nhap theo format trong ngoac kia kia`, vi du nhap la 04/12/1992
myname2
myname2

Tổng số bài gửi : 66
Points : 90
Join date : 27/09/2010
Age : 31
Đến từ : Hà Nội

https://facebook.com/tuanhai

Về Đầu Trang Go down

Week 12 (Full) Empty Re: Week 12 (Full)

Bài gửi by Sponsored content


Sponsored content


Về Đầu Trang Go down

Về Đầu Trang

- Similar topics

 
Permissions in this forum:
Bạn không có quyền trả lời bài viết