Showing posts with label C. Show all posts
Showing posts with label C. Show all posts

Thursday, April 16, 2015

source code of separation of string into substring at specified delimeter in C(Line parsing)

In writing a program , we may reach to a situation where we need to read the string and seperate the string depending upon certain symbol or delimeter. Here I have written a simple program to parse the string with new line character.

Requirement:

let's say I have a string as "this \n is  \n a \n test \n program" and I need to read the string and seperate the string. To acheive this, we have a strtok function included in string.h.

Source code:
#include <stdio.h>
#include <string.h>


int main()
{
	char *token, *remstr=NULL ;
char str[] = " this \n is \n the \n test\n program";
token = strtok_r(str,"\n",&remstr);



        

		while(token != NULL)
		{
		
		    printf("here i=%s\n",token);
		    printf("remstr=%s\n",remstr);

		    token = strtok_r(NULL, "\n", &remstr);
		
		}

		return 0;

}

strtok function takes the string and the seperation symbol and this function scan the seperator and save the seperated sub string at token .  At remstr the remaining string is stored and the loop is repeated until there is substring at the remaining string. The loop is repeated until token has null value. When the last substirng is reached, the strtok function will produce the null value and this null value is the indication of end of string.

Note: At the end of string , the remaining string will store a null value in mac where as in ubuntu/linux the empty string is stored.

similarly we can seperate the string to sub string depending upon different seperator as per our requirement  in the program using strtok or strtok_r function included in string.h header.


In large program , we may come across the situation that we need to accumulate the seperated token or substring in to the array of string  and return the array of substing to the main calling function to perform the specific task for each substring.

for accmulation of substring , I have used the list of glib library.

source code:
#include <stdio.h>
#include <string.h>
#include <glib.h>

char *col_trim_whitespace(char *str)
{
  char *end;

  // Trim leading space
  while(isspace(*str)) str++;

  if(*str == 0)  // All spaces?
    return str;

  // Trim trailing space
  end = str + strlen(str) - 1;
  while(end > str && isspace(*end)) end--;

  // Write new null terminator
  *(end+1) = 0;

  return str;
}


GSList* line_parser(char *str,GSList* list)
{


        
        char *token, *remstr=NULL ;
 
		token = strtok_r(str,"\n",&remstr);


		while(token != NULL)
		{
			if(token[0] == ' ')
			{

			token = col_trim_whitespace(token);
			if(strcmp(token,"")==0)
		         {
		             token = strtok_r(NULL, "\n", &remstr);
		              continue;
		          }
		    }

		    list = g_slist_append(list, token);
            token = strtok_r(NULL,"\n",&remstr);
            
             


		}


        

		
		return list;


}

int main()
{
	

 int *av,i,j,length;
 i=0;


char str[] = " this";

 GSList* list = NULL;

 
GSList *list1 = line_parser(str,list);
// printf("The list is now %d items long\n", g_slist_length(list));
 length = g_slist_length(list1);
for(int j=0;j<length;j++)printf("string = %s\n",(char *)g_slist_nth(list1,j)->data);
return 0;
}

Monday, March 23, 2015

Installation of CMake and using cmake for simple C program for creating of makefile

Installation of makefile and  using cmake for simple C program for  creating of makefile

Makefile is a file which tells how to compile and link a program. The instruction of compiling a source file , including library file and linking the file to produce the final binary file is written in Makefile. In Linux based system , If we are using an IDE then makefile is created by IDE. However if we are not using IDE and simply compiling and linking through command line, in such case we need to create MakeFile. CMake is a tool used to easy generation of cross platform Makefile.


here I have presented the use of Cmake to create a MakeFile in simple ways. The following procedure are tested in Linux/Mac OS.

1) Installation of CMake:

first install CMake. It is available in all the platforms. In mac, linux Cmake-gui is also available with GUI feature available. Be sure that command line feature is also installed along with GUI in linux and Mac OS.

Just type cmake to ensure that cmake command line is available in linux and mac.


2) creation of simple C project file  named cmake.c

 first let us create a simple C file as
#include <stdio.h>



int main()


printf("this  is the test file");


2) create CMakeLists.txt along with source file

After creation of source file , next we need a CMakeLists.txt file. This file is used by the Cmake to create a Makefile.

cmake_minimum_required (VERSION 2.6)

set(TARGET learn)

set(SOURCE cmake.c)



add_executable(${TARGET} ${SOURCE})

message("Success")




here we set learn as TARGET and cmake.c as SOURCE  and we want our makefile to create a executable file named as learn .

3) Generation of Makefile

first create a new folder and name it "build" so that all the file generated by Cmake are placed here. This new folder is not a compulsary one but is created to manage the files.

This makefile can be generated in two ways . Either by cmake-gui or command line

a) using GUI

 first open the gui of cmake . then there is input fields as "where is the source code"
 and where ti build the binaries. Just browse to the source code folder in the first input field and browse to the recently created build folder in the later input box.

 then finally press the Configure and Generate button of the GUI.

 then after this makefile is created in the build directory. make sure to see it.




 b) using command line

 first move the the build directory.
 then  input the command
   cmake ..

   this will create the makefile in the build folder.



4) running of MakeFile recently created

   then move to the folder build as MakeFile created is placed here.

   run the command

    make

    this will create the binary file learn as we have named our binary to be learn in earlier CMakeListes.txt at the start.

    5) so run the executable as

      finally move to the folder inside build where learn executables is created and run the command

      ./learn

      wow we get the output.




Wednesday, November 28, 2012

Quiz game in C language complete source code download


C language is the basic language in the programming field. every programmer starts the programming from the C language. Generally in the IT field like Computer Engineerung or any related computer field, we are taught the C language and at the end of the class, we are asked to do a simple project  implementing C language. At this situation we may be in delime about what to do in the project as C project.In that particular condition  The Quiz game can be one of the alternative to us. It implemts almost every part we learn in the course from simple input/output to the file implementation.

INTRODUCTION

Quiz game is a very popular General Knowledge Game. The quiz game increases the IQ knowledge of the player. It is used to check the knowledge within us.
The provided source code is the simple Quiz game programmed  implementing C language. In this programe The several question are provided  to the player.The player are provided with 4 option in it. Player is all need to choice the suitable option from the 4 option available in the screen. The player need to type either A,B,C,or D according to the suitable answer provided in it.
The player will score the points with each correct answer provided. If the player is unable to answer the question, then correct answer is provided. The user are given 3 chance in it. The game will be terminated with score and suggestion displayed if the user goes to incorrect answer for consequitive 3 chances.

At the beginning of the game menu is provided .according to the menu user need to proceed in it. Also File is used in it to store the points scored by the player. The player can see the highest score through this file through the menu .
24 question are included in it,however we can add further question as per our need.


DOWNLOAD SOURCECODE WITH OUTPUT HERE

I hope this article will be helpful in the project regarding  the C programming project. The quiz program is really intresting project to begin programming project for the beginners. The code is simple and clean.  I appreciate the comment and any feedback ,Please.

Wednesday, November 21, 2012

Tic-tac- toe game sourcecode in C

INTRODUCTION

Tic-tac-toe is a simple two player game. It is a pen and paper game.It is mostly played especially in childhood between two player. each player tries to complete the boxes horizontally,vertically or diagonally. The player to finished first is declared the winner.

This is a simple  game without the AI(artificial intelligence). This code doesnot contain the AI i.e player cannot play against the computer player.


HERE IS THE COMPLETE CODE:

/* This is the complete source code of tic tac toe in C language. It is perfectly run in the codeblocks IDE */

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include <windows.h>



int board[10] = {2,2,2,2,2,2,2,2,2,2};
int turn = 1,flag = 0;
int player,comp;

void menu();
void go(int n);
void start_game();
void check_draw();
void draw_board();
void player_first();
void put_X_O(char ch,int pos);
 COORD coord={0,0}; // this is global variable
                                    //center of axis is set to the top left cornor of the screen
void gotoxy(int x,int y)
{
    coord.X=x;
    coord.Y=y;
    SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),coord);
}



 void main()
{
 system("cls");
 menu();
 getch();

}

void menu()
{
 int choice;
 system("cls");
 printf("\n--------MENU--------");
 printf("\n1 : Play with X");
 printf("\n2 : Play with O");
 printf("\n3 : Exit");
 printf("\nEnter your choice:>");
 scanf("%d",&choice);
 turn = 1;
 switch (choice)
 {
  case 1:
   player = 1;
   comp = 0;
   player_first();
   break;
  case 2:
   player = 0;
   comp = 1;
   start_game();
   break;
  case 3:
   exit(1);
  default:
   menu();
 }
}

int make2()
{
 if(board[5] == 2)
  return 5;
 if(board[2] == 2)
  return 2;
 if(board[4] == 2)
  return 4;
 if(board[6] == 2)
  return 6;
 if(board[8] == 2)
  return 8;
 return 0;
}

int make4()
{
 if(board[1] == 2)
  return 1;
 if(board[3] == 2)
  return 3;
 if(board[7] == 2)
  return 7;
 if(board[9] == 2)
  return 9;
 return 0;
}

int posswin(int p)
{
// p==1 then X   p==0  then  O
 int i;
 int check_val,pos;

 if(p == 1)
  check_val = 18;
 else
  check_val = 50;

 i = 1;
 while(i<=9)//row check
 {
  if(board[i] * board[i+1] * board[i+2] == check_val)
  {
   if(board[i] == 2)
    return i;
   if(board[i+1] == 2)
    return i+1;
   if(board[i+2] == 2)
    return i+2;
  }
  i+=3;
 }

 i = 1;
 while(i<=3)//column check
 {
  if(board[i] * board[i+3] * board[i+6] == check_val)
  {
   if(board[i] == 2)
    return i;
   if(board[i+3] == 2)
    return i+3;
   if(board[i+6] == 2)
    return i+6;
  }
  i++;
 }

 if(board[1] * board[5] * board[9] == check_val)
 {
  if(board[1] == 2)
   return 1;
  if(board[5] == 2)
   return 5;
  if(board[9] == 2)
   return 9;
 }

 if(board[3] * board[5] * board[7] == check_val)
 {
  if(board[3] == 2)
   return 3;
  if(board[5] == 2)
   return 5;
  if(board[7] == 2)
   return 7;
 }
 return 0;
}

void go(int n)
{
 if(turn % 2)
  board[n] = 3;
 else
  board[n] = 5;
 turn++;
}

void player_first()
{
 int pos;

 check_draw();
 draw_board();
 gotoxy(30,18);
 printf("Your Turn :> ");
 scanf("%d",&pos);

 if(board[pos] != 2)
  player_first();

 if(pos == posswin(player))
 {
  go(pos);
  draw_board();
  gotoxy(30,20);
  //textcolor(128+RED);
  printf("Player Wins");
  getch();
  exit(0);
 }

 go(pos);
 draw_board();
 start_game();
}

void start_game()
{
 // p==1 then X   p==0  then  O
 if(posswin(comp))
 {
  go(posswin(comp));
  flag = 1;
 }
 else
 if(posswin(player))
  go(posswin(player));
 else
 if(make2())
  go(make2());
 else
  go(make4());
 draw_board();

 if(flag)
 {
  gotoxy(30,20);
  //textcolor(128+RED);
  printf("Computer wins");
  getch();
 }
 else
  player_first();
}

void check_draw()
{
 if(turn > 9)
 {
  gotoxy(30,20);
  //textcolor(128+RED);
  printf("Game Draw");
  getch();
  exit(0);
 }
}

void draw_board()
{
 int j;

 for(j=9;j<17;j++)
 {
  gotoxy(35,j);
  printf("|       |");
 }
 gotoxy(28,11);
 printf("-----------------------");
 gotoxy(28,14);
 printf("-----------------------");

 for(j=1;j<10;j++)
 {
  if(board[j] == 3)
   put_X_O('X',j);
  else
  if(board[j] == 5)
   put_X_O('O',j);
 }
}

void put_X_O(char ch,int pos)
{
 int m;
 int x = 31, y = 10;

 m = pos;

 if(m > 3)
 {
  while(m > 3)
  {
   y += 3;
   m -= 3;
  }
 }
 if(pos % 3 == 0)
  x += 16;
 else
 {
  pos %= 3;
  pos--;
  while(pos)
  {
   x+=8;
   pos--;
  }
 }
 gotoxy(x,y);
 printf("%c",ch);
}



OUTPUT: