How to save entered strings and integers in C - c

Can anyone help me on my code. What it should do is when I enter "create 6 5" its supposed to create a 6x5 rectangular shape with *'s, but will not show yet unless I entered "show".
This is the code i'm working on, it is not correct yet, still figuring out how to do it.
i'm new in programming.
char s[100];
char *s1 = "show";
char *s2 = "create";
int main()
{
int zWidth = 0, zHeight = 0, zLoop = 0, aLoop = 0;
do
{
scanf("%s %d %d", &s, &zWidth, &zHeight);
}
while (strcmp(s1, s) != 0);
if(strcmp(s2, s) == 0)
{
//To draw the first horizontal line
for(zLoop = 0; zLoop < zWidth; zLoop++)
printf("*");
printf("\n");
//Drawing the vertical lines
for(zLoop = 2; zLoop < zHeight; zLoop++)
{
printf("*");
for(zLoop = 0; aLoop < zWidth-2; aLoop++)
printf("*");
printf("*\n");
}
//Last horizontal Line
for(zLoop = 0; zLoop < zWidth; zLoop++)
printf("*");
printf("\n");
}
return 0;
}

#include <stdio.h>
enum command_state {
SHOW, CREATE, QUIT, HELP, INVALID
};
char Command_line[100];
const char *Show = "show";
const char *Create = "create";
const char *Quit = "quit";
const char *Help = "help";
const char *QMark = "?";
enum command_state command(void){
if(fgets(Command_line, sizeof(Command_line), stdin) != NULL){
char operation[16];
sscanf(Command_line, "%15s", operation);
if(!strcmp(operation, Show))
return SHOW;
else if(!strcmp(operation, Create))
return CREATE;
else if(!strcmp(operation, Quit))
return QUIT;
else if(!strcmp(operation, Help) || !strcmp(operation, QMark))
return HELP;
else
return INVALID;
}
return QUIT;//input EOF
}
int main(void){
int rWidth = 0, rHeight = 0, aLoop = 1;
while(aLoop){
switch(command()){
case SHOW :
if(rWidth == 0 || rHeight == 0)
printf("execute create is required before\n");
else {
int h, w;
for(h = 0; h < rHeight; h++) {
for(w = 0; w < rWidth; w++)
printf("*");
printf("\n");
}
}
break;
case CREATE :
if(2!=sscanf(Command_line, "create %d %d", &rWidth, &rHeight) ||
rWidth < 1 || rHeight < 1){
rWidth = rHeight = 0;
printf("invalid create command\n");
}
break;
case QUIT :
aLoop = 0;
break;
case HELP :
printf(
"help or ? : this\n"
"create w h: set to size of rectangle width and height\n"
"show : draw filled rectangle\n"
"quit : end of program\n"
);
break;
default :
printf("invalid command\n");
}
}
return 0;
}

Related

SDL with C - Blocks remains after being played

I have been working on a game that is a Stacker. Everything works fine, but after you have played and started over the blocks from the previous game still remain there.
Could anyone help me with this problem?
#include <SDL/SDL.h>
#include <SDL/SDL_image.h>
#include <SDL/SDL_mixer.h>
#include <stdio.h>
#include <stdlib.h>
#define BASE_TIME_INTERVAL 80
#define SPEED_INCREASE 1.03
#define GAME_ROWS 15
#define GAME_COLUMNS 7
#define MIN(a, b) ((a < b) ? a : b)
#define MAX(a, b) ((a > b) ? a : b)
int array_matrix[GAME_ROWS][GAME_COLUMNS];
//void save();
int credit = 0;
int in = 0;
int out = 0;
int inGame = 0;
static SDL_Surface *screen;
//Sprites
static SDL_Surface *square;
static SDL_Surface *background;
static SDL_Surface *grid;
static SDL_Surface *main_ui;
static SDL_Surface *award;
//Text Credits Sprites
static SDL_Surface *credits;
static SDL_Surface *number;
//Sounds
Mix_Chunk *soundPlace = NULL;
Mix_Chunk *soundGameOver = NULL;
Mix_Chunk *soundCredit = NULL;
FILE * fptr;
void print_board() {
int i, j;
SDL_Rect src, dest;
for (i = 0; i < 15; i++) {
for (j = 0; j < 7 ; j++) {
if (array_matrix[i][j] == 1) {
src.x = 0;
src.y = 0;
src.w = 65;
src.h = 65;
dest.x = j * 67 + 227;
dest.y = i * 67 + 240;
dest.w = 65;
dest.h = 65;
SDL_BlitSurface(square, &src, screen, &dest);
}
}
}
}
void update_board(int x_pos, int length, int level) {
int underflow_ammt = length - 1;
int j;
if (x_pos < underflow_ammt)
length = length - (underflow_ammt - x_pos);
x_pos = MAX(0, x_pos-underflow_ammt);
for (j = 0; j < GAME_COLUMNS; j++)
array_matrix[GAME_ROWS - level][j] = 0;
for (j = x_pos; j < x_pos + length; j++) {
array_matrix[GAME_ROWS - level][MIN(j, GAME_COLUMNS-1)] = 1;
}
}
int get_new_length(int level) {
int i;
int length = 0;
for (i = 0; i < GAME_COLUMNS; i++) {
if (array_matrix[GAME_ROWS - level][i] == 1) {
length++;
if (level != 1) {
if (array_matrix[GAME_ROWS - (level - 1)][i] != 1) {
array_matrix[GAME_ROWS - level][i] = 0;
length--;
}
}
}
if ((level == 4 && length == 3) || (level == 10 && length == 2)) {
length--;
}
}
return length;
}
void draw_background(){
SDL_BlitSurface(background, NULL, screen, NULL);
SDL_BlitSurface(main_ui, NULL, screen, NULL);
SDL_BlitSurface(award, NULL, screen, NULL);
SDL_BlitSurface(grid, NULL, screen, NULL);
}
void draw_credits(){
SDL_Rect destCredits;
SDL_Rect destNumber;
switch (credit)
{
case 0:
number = IMG_Load("assets/0.png");
break;
case 1:
number = IMG_Load("assets/1.png");
break;
case 2:
number = IMG_Load("assets/2.png");
break;
case 3:
number = IMG_Load("assets/3.png");
break;
case 4:
number = IMG_Load("assets/4.png");
break;
case 5:
number = IMG_Load("assets/5.png");
break;
case 6:
number = IMG_Load("assets/6.png");
break;
case 7:
number = IMG_Load("assets/7.png");
break;
case 8:
number = IMG_Load("assets/8.png");
break;
case 9:
number = IMG_Load("assets/9.png");
break;
}
if (number == NULL) {
printf("Unable to load number png.\n");
}
destCredits.x = 300;
destCredits.y = 1300;
destNumber.x = 550;
destNumber.y = 1305;
SDL_BlitSurface(credits, NULL, screen, &destCredits);
SDL_BlitSurface(number, NULL, screen, &destNumber);
}
void game_loop() {
int time_delay = BASE_TIME_INTERVAL;
int left_or_right = 1;
int current_level = 1;
int length = 3;
int x_pos = 0;
int quit = 0;
int underflow_ammt = length - 1;
SDL_Event event;
while (!quit) {
while (SDL_PollEvent(&event)) {
switch(event.type) {
case SDL_KEYDOWN:
if (event.key.keysym.sym == SDLK_SPACE && inGame == 1) {
length = get_new_length(current_level);
underflow_ammt = length - 1;
if (current_level >= 15 || length == 0) {
Mix_PlayChannel( -1, soundGameOver, 0 );
inGame = 0;
time_delay = BASE_TIME_INTERVAL;
left_or_right = 1;
current_level = 1;
length = 3;
x_pos = 0;
underflow_ammt = length - 1;
}
else{
Mix_PlayChannel( -1, soundPlace, 0 );
current_level++;
time_delay = time_delay/SPEED_INCREASE;
}
}
if (event.key.keysym.sym == SDLK_2 && credit < 9){
credit++;
in++;
save();
Mix_PlayChannel( -1, soundCredit, 0 );
}
if (event.key.keysym.sym == SDLK_1 && credit > 0 && inGame == 0){
credit--;
out++;
save();
Mix_PlayChannel( -1, soundCredit, 0 );
inGame = 1;
}
if (event.key.keysym.sym == SDLK_ESCAPE){
quit = 1;
exit(0);
}
break;
case SDL_QUIT:
quit = 1;
exit(0);
break;
}
}
if (!quit) {
SDL_FillRect(screen, NULL, 0x000000);
if (x_pos >= GAME_COLUMNS + (underflow_ammt - 1))
left_or_right = -1;
if (x_pos <= 0)
left_or_right = 1;
update_board(x_pos, length, current_level);
draw_background();
if (inGame == 1)
print_board();
draw_credits();
SDL_Flip(screen);
x_pos = x_pos + left_or_right;
SDL_Delay(time_delay);
}
}
}
/*
void save(){
fptr = fopen("data.xml", "w");
fprintf(fptr,"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
fprintf(fptr,"<Data>\n");
fprintf(fptr," <credits>%d</credits>\n",credit);
fprintf(fptr," <IN>%d</IN>\n",in);
fprintf(fptr," <OUT>%d</OUT>\n",out);
fprintf(fptr,"</Data>\n");
fclose(fptr);
}
*/
void init(){
if (SDL_Init(SDL_INIT_VIDEO) != 0) {
printf("Unable to initialize SDL: %s\n", SDL_GetError());
}
screen = SDL_SetVideoMode(768, 1366, 16, SDL_DOUBLEBUF | SDL_HWSURFACE | SDL_FULLSCREEN);
if (screen == NULL) {
printf("Unable to set video mode: %s\n", SDL_GetError());
}
int imgFlags = IMG_INIT_PNG;
if( !( IMG_Init( imgFlags ) & imgFlags ) )
{
printf( "SDL_image could not initialize! SDL_image Error: %s\n", IMG_GetError() );
}
if (SDL_Init(SDL_INIT_AUDIO) < 0){
printf("Unable to set audio mode: %s\n", SDL_GetError());
}
//Initialize SDL_mixer
if( Mix_OpenAudio( 44100, MIX_DEFAULT_FORMAT, 2, 2048 ) < 0 )
printf( "SDL_mixer could not initialize! SDL_mixer Error: %s\n", Mix_GetError());
}
void loadMedia(){
background = IMG_Load("assets/background.png");
if (background == NULL)
printf("Unable to load background png.\n");
square = IMG_Load("assets/square.png");
if (square == NULL)
printf("Unable to load square png.\n");
credits = IMG_Load("assets/credits.png");
if (credits == NULL)
printf("Unable to load credits png.\n");
grid = IMG_Load("assets/grid.png");
if (grid == NULL)
printf("Unable to load grid png.\n");
main_ui = IMG_Load("assets/main_ui.png");
if (main_ui == NULL)
printf("Unable to load main_ui png.\n");
soundPlace = Mix_LoadWAV("assets/place.wav");
if(soundPlace == NULL)
printf( "Failed to load place sound effect! SDL_mixer Error: %s\n", Mix_GetError() );
soundGameOver = Mix_LoadWAV("assets/gameover.wav");
if(soundGameOver == NULL)
printf( "Failed to load gameover sound effect! SDL_mixer Error: %s\n", Mix_GetError() );
soundCredit = Mix_LoadWAV("assets/credit.wav");
if( soundCredit == NULL )
printf( "Failed to load credit sound effect! SDL_mixer Error: %s\n", Mix_GetError() );
}
void close(){
SDL_FreeSurface(square);
SDL_FreeSurface(background);
SDL_FreeSurface(credits);
SDL_FreeSurface(grid);
SDL_FreeSurface(main_ui);
SDL_FreeSurface(number);
Mix_FreeChunk(soundPlace);
Mix_FreeChunk(soundGameOver);
Mix_FreeChunk(soundCredit);
Mix_Quit();
IMG_Quit();
SDL_Quit();
}
int main(int argc, char *argv[])
{
init();
loadMedia();
game_loop();
close();
return 0;
}
I using:
SDL 1.2.15
SDL_image 1.2.12
SDL_mixer 1.2.12

Why am I getting this message in hackerrank "~ no response on stdout ~"? I don't know what I am missing>

Why am I getting this message in hackerrank "~ no response on stdout ~"? I don't know what I am missing?
I am bit frustrated right now because I have no clue about what to do.
So I was left with only choice to post this query on Stackoverflow.
Here is the link to the problem
Here is my complete code:
char* readline();
// Complete the countingValleys function below.
int countingValleys(int n, char* s)
{
int dwnhl = 0, level = 0;
bool frmsurface = true;
int k = strlen(s);
for (int i = 0; i < k; i++)
{
if (level == 0)
{
frmsurface = true;
}
if (s[i] == 'D')
{
level--;
if ((level < 0) && (frmsurface == true))
{
dwnhl++;
frmsurface = false;
//printf("went downhill %d ",i);
}
}
else if (s[i] == 'U')
{ //printf("went uphill %d ",i);
level++;
}
// printf("\nhello - %c",s[i]);
}
printf("\nNumber of downhill = %d \n", dwnhl);
return (dwnhl);
}
int main()
{
FILE* fptr = fopen(getenv("OUTPUT_PATH"), "w");
char* n_endptr;
char* n_str = readline();
int n = strtol(n_str, &n_endptr, 10);
if (n_endptr == n_str || *n_endptr != '\0')
{
exit(EXIT_FAILURE);
}
char* s = readline();
int result = countingValleys(n, s);
printf("%d\n", result);
return 0;
}
char* readline()
{
size_t alloc_length = 1024;
size_t data_length = 0;
char* data = malloc(alloc_length);
while (true)
{
char* cursor = data + data_length;
char* line = fgets(cursor, alloc_length - data_length, stdin);
if (!line)
{
break;
}
data_length += strlen(cursor);
if (data_length < alloc_length - 1 || data[data_length - 1] == '\n')
{
break;
}
size_t new_length = alloc_length << 1;
data = realloc(data, new_length);
if (!data)
{
break;
}
alloc_length = new_length;
}
if (data[data_length - 1] == '\n')
{
data[data_length - 1] = '\0';
}
data = realloc(data, data_length);
return data;
}
One problem is the way you handle frmsurface
The first time you enter the loop frmsurface is set to true. If the events are UUDD, your code will still count a "valley" because you don't clear frmsurface when you go up.
Instead of
if(level==0)
{
frmsurface=true;
}
you could try:
frmsurface = (level == 0);
but I don't really understand why you want the boolean. Just test for level == 0 instead. Something like:
if(s[i]=='D')
{
if(level==0)
{
dwnhl++;
}
level--;
}
else if (s[i]=='U')
{
level++;
}
Also I wonder if this line:
printf("\nNumber of downhill = %d \n", dwnhl);
must be removed.
Notice that
int k=strlen(s);
for(int i=0;i<k;i++)
could probably just be
for(int i=0;i<n;i++)
^
as n is passed to the function

Print the correct Morse code for alpha entry

I now need to output the Morse code equivalent of alphanumeric input. My condition for check this is an if loop: I try to look at each element of input array with each element of the alpha array but a match never seems to be found. I am not sure if I am using the correct method. I try to de-reference the point to input and compare the value with each element of alpha until a match is found. If no match is found then an error occurs.
Not working:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
#include <ctype.h>
int main(void)
{
char *morse[] = {"/",
".-","-...","-.-.","-..",".","..-.","--","....","..",".---",
"-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-",
"..-","...-",".--","-..-","-.--","--..",
"-----",".----","..---","...--","....-",".....","-....","--...","---..","----."};
char *alpha[]= {" ",
"A","B","C","D","E","F","G","H","I","J",
"K","L","M","N","O","P","Q","R","S","T",
"U","V","W","X","Y", "Z",
"0", "1","2","3","4","5","6","7","8","9"};
char *print_array[50];
int print_array_index = 0;
char hold[50];
int hold_index = 0;
char input[200];
int i = 0;
printf("welcome to the Morse translator.\n");
printf("Enter input: ");
fgets(input, sizeof(input), stdin);
char *p;
for (p=input; *p !='\0';++p)
{
*p = toupper(*p);
}
if (input[0]=='-' || input[0]=='.')
{
while (input[i] !='\0') {
if (input[i] ==' ' || input[i] == '\n')
{
hold[hold_index] = '\0';
bool found = false;
for (int x = 0; x < sizeof(morse) / sizeof(char *); x++)
{
if (strcmp(morse[x], hold) == 0)
{
print_array[print_array_index++] = alpha[x];
found = true;
break;
}
}
if (!found)
{
fprintf(stderr, "invalid Morse code!\n");
}
hold_index = 0;
}
else
{
hold[hold_index++] = input[i];
}
i++;
}
for (int x = 0; x < print_array_index; x++)
{
printf("%s", print_array[x]);
}
printf("\n");
}
else if (isalnum(input[0]))
{
while (input[i]!='\0')
{
if (input[i] ==' ' || input[i] == '\n')
{
bool found = false;
for (int x=0; x < sizeof(alpha)/sizeof (char*);x++)
{
if (alpha[x]==input[i])
{
print_array [print_array_index++] = alpha[x];
found = true;
break;
}
}
if (!found)
{
fprintf(stderr, "Invalid input!\n");
}
hold_index = 0;
}
i++;
}
for (int x=0; x < print_array_index; x++)
{
printf("%s",print_array[x]);
}
printf("\n");
}
return 0;
}
part of else if (isalnum(input[0])){ should be something like
else if (isalnum(input[0])){
while (input[i]!='\0' && input[i]!='\n'){
bool found = false;
for (int x=0; x < sizeof(alpha)/sizeof(char*);x++){
if (*alpha[x]==input[i]){
print_array[print_array_index++] = morse[x];
found = true;
break;
}
}
if(!found){
fprintf(stderr, "Invalid input!\n");
}
i++;
}
for (int x=0; x < print_array_index; x++){
printf("%s", print_array[x]);
}
printf("\n");
}

char array input with space

my program works fine if i give hard code value to char *w="ls -l" but i am trying to take input form user not working help my code:: using input error occur
i don't understand the concept of fgets using fgets its gives the garbig value to execv
#include<stdio.h>
#include<sys/wait.h>
#include<stdbool.h>
void func(char **arr, char *w)
{
int i = 0, j = 0, k = 0;
char temp[100];
for (i = 0; i < 100; i++)
{
if (w[i] == '')
{
arr[k] = temp;
arr[k+1] = NULL;
break;
}
if (w[i] == ' ')
{
arr[k] = temp;
k++;
j = 0;
}
else
{
temp[j] = w[i];
j++;
}
}
}
int main()
{
char *n = "/bin/ls";
char *arr[10] = {''};
char p[100] = {''};
char *w = "ls -l";
int i = 0;
//printf("bilal-hassan-qadri $ >>");
//fgets(p, 100, stdin);
arr[2] = NULL;
bool found = false;
for (i = 0; i < sizeof(w); i++)
{
if (w[i] == ' ')
{
found=true;
func(arr,w);
break;
}
}
if (!found)
arr[0] = w;
int status;
int id = fork();
if (id == 0)
{
if (execv(n,arr) < 0)
{
printf("invalid commandn");
}
else
{
printf("ninvalid command");
}
}
else
{
wait(&status);
}
}
In the function func, You have to copy the string to elements of arr
instead of just passing the address of temp, which will vanish on leaving the function.
You can use strdup instead of copy_string if your system supports it.
You have to terminate the string in temp before copying it.
Empty string constant '' seems invalid. You shouldn't use it.
fgets stores new-line character \n if it exists. Check for it and remove if it isn't wanted.
Fixed code:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<sys/wait.h>
#include<stdbool.h>
char *copy_string(const char *str) {
char *s = malloc(strlen(str) + 1);
if (s) strcpy(s, str); else {perror("malloc"); exit(1);}
return s;
}
void func(char **arr, char *w)
{
int i = 0, j = 0, k = 0;
char temp[100];
for (i = 0; i < 100; i++)
{
if (w[i] == '\0' || w[i] == '\n')
{
temp[j] = '\0';
arr[k] = copy_string(temp);
arr[k+1] = NULL;
break;
}
if (w[i] == ' ')
{
temp[j] = '\0';
arr[k] = copy_string(temp);
k++;
j = 0;
}
else
{
temp[j] = w[i];
j++;
}
}
}
int main(void)
{
char *n = "/bin/ls";
char *arr[10] = {NULL};
char p[100] = {0};
char *w = "ls -l";
int i = 0;
//printf("bilal-hassan-qadri $ >>");
fgets(p, 100, stdin);
w = p;
arr[2] = NULL;
bool found = false;
for (i = 0; w[i] != '\0'; i++)
{
if (w[i] == ' ')
{
found=true;
func(arr,w);
break;
}
}
if (!found)
arr[0] = w;
int status;
int id = fork();
if (id == 0)
{
if (execv(n,arr) < 0)
{
printf("invalid commandn");
}
else
{
printf("ninvalid command");
}
}
else
{
wait(&status);
for (i = 0; arr[i] != NULL; i++) free(arr[i]);
}
return 0;
}

Printing string pointers in c

So, essentially I have two files:
File 1:
//
// main.c
// frederickterry
//
// Created by Rick Terry on 1/15/15.
// Copyright (c) 2015 Rick Terry. All rights reserved.
//
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int size (char *g) {
int ofs = 0;
while (*(g+ofs) != '\0') {
++ofs;
}
return ofs;
}
int parse(char *g) {
// Setup
char binaryConnective;
int negated = 0;
// Looking for propositions
int fmlaLength = size(g);
if(fmlaLength == 0) {
return 1;
}
if(fmlaLength == 1) {
if(g[0] == 'p') {
return 1;
} else if (g[0] == 'q') {
return 1;
} else if (g[0] == 'r') {
return 1;
} else {
return 0;
}
}
// Now looking for negated preposition
if(fmlaLength == 2) {
char temp[100];
strcpy(temp, g);
if(g[0] == '-') {
negated = 1;
int negatedprop = parse(g+1);
if(negatedprop == 1) {
return 2;
}
}
}
// Checking if Binary Formula
char arrayleft[50];
char arrayright[50];
char *left = "";
char *right = "";
int numLeft = 0;
int numRight = 0;
int bclocation = 0;
int binarypresent = 0;
if(fmlaLength != 1 && fmlaLength != 2) {
if(g[0] == '-') {
int negatedBinary = parse(g+1);
if(negatedBinary == 1 || negatedBinary == 2 || negatedBinary == 3) {
return 2;
} else {
return 0;
}
}
int i = 0;
int l = 0;
int p = strlen(g);
for(l = 0; l < strlen(g)/2; l++) {
if(g[l] == '(' && g[p-l-1] == ')') {
i++;
}
}
for(int q = i; q < strlen(g); q++) {
if(g[q] == '(') {
numLeft++;
} else if(g[q] == ')') {
numRight++;
}
arrayleft[q] = g[q];
//printf("%c", arrayleft[i]);
//printf("%s", left);
if((numRight == numLeft) && (g[q+1] == 'v' || g[q+1] == '>' || g[q+1] == '^')) {
arrayleft[q+1] = '\0';
bclocation = q+1;
binaryConnective = g[q+1];
binarypresent = 1;
// printf("The binary connecive is: %c\n", binaryConnective);
break;
}
}
if(binarypresent == 0) {
return 0;
}
int j = 0;
for(int i = bclocation+1; i < strlen(g)-1; i++) {
arrayright[j] = g[i];
j++;
}
arrayright[j] = '\0';
left = &arrayleft[1];
right = &arrayright[0];
//printf("Printed a second time, fmla 1 is: %s", left);
int parseleft = parse(left);
// printf("Parse left result: %d\n", parseleft);
if(parseleft == 0) {
return 0;
}
int parseright = parse(right);
if(parseright == 0) {
return 0;
}
// printf("Parse right result: %d\n", parseleft);
if(negated == 1) {
return 2;
} else {
return 3;
}
}
return 0;
}
int type(char *g) {
if(parse(g) == 1 ||parse(g) == 2 || parse(g) == 3) {
if(parse(g) == 1) {
return 1;
}
/* Literals, Positive and Negative */
if(parse(g) == 2 && size(g) == 2) {
return 1;
}
/* Double Negations */
if(g[0] == '-' && g[1] == '-') {
return 4;
}
/* Alpha & Beta Formulas */
char binaryConnective;
int numLeft = 0;
int numRight = 0;
int bclocation = 0;
int binarypresent = 0;
int i = 0;
if(g[0] == '(') {
i++;
}
if(g[0] == '-') {
i++;
if(g[1] == '(') {
i++;
}
}
for(i; i < strlen(g); ++i) {
if(g[i] == '(') {
numLeft++;
} else if(g[i] == ')') {
numRight++;
}
if(numRight == numLeft) {
if(g[i+1] == 'v' || g[i+1] == '>' || g[i+1] == '^') {
bclocation = i+1;
binaryConnective = g[i+1];
binarypresent = 1;
break;
}
}
}
/* Connective established */
if(binaryConnective == '^') {
if(g[0] == '-') {
return 3;
} else {
return 2;
}
} else if(binaryConnective == '>') {
if(g[0] == '-') {
return 2;
} else {
return 3;
}
} else if (binaryConnective == 'v') {
if(g[0] == '-') {
return 2;
} else {
return 3;
}
}
}
return 0;
}
char bin(char *g) {
char binaryConnective;
char arrayLeft[50];
int numLeft = 0;
int numRight = 0;
int bclocation = 0;
int i = 0;
if(g[0] == '(') {
i++;
}
if(g[0] == '-') {
i++;
if(g[1] == '(') {
i++;
}
}
for(i; i < strlen(g); ++i) {
if(g[i] == '(') {
numLeft++;
} else if(g[i] == ')') {
numRight++;
}
int j = 0;
arrayLeft[j++] = g[i];
if(numRight == numLeft) {
if(g[i+1] == 'v' || g[i+1] == '>' || g[i+1] == '^') {
arrayLeft[i+1] = '\0';
bclocation = i+1;
binaryConnective = g[i+1];
return binaryConnective;
}
}
}
return binaryConnective;
}
char *partone(char *g) {
char binaryConnective;
char arrayLeft[50];
char arrayRight[50];
int numLeft = 0;
int numRight = 0;
int bclocation = 0;
int i = 0;
if(g[0] == '(') {
i++;
}
if(g[0] == '-') {
i++;
if(g[1] == '(') {
i++;
}
}
int j = 0;
for(i; i < strlen(g); ++i) {
if(g[i] == '(') {
numLeft++;
} else if(g[i] == ')') {
numRight++;
}
arrayLeft[j] = g[i];
if(numRight == numLeft) {
if(g[i+1] == 'v' || g[i+1] == '>' || g[i+1] == '^') {
arrayLeft[j+1] = '\0';
bclocation = i+1;
binaryConnective = g[i+1];
break;
}
}
j++;
}
int m = 0;
for(int k = bclocation+1; k < strlen(g)-1; k++) {
arrayRight[m] = g[k];
m++;
}
arrayRight[m] = '\0';
char* leftSide = &arrayLeft[0];
// printf("%s\n", leftSide);
// printf("%s\n", rightSide);
int k = 0;
k++;
return leftSide;
}
char *parttwo(char *g) {
char binaryConnective;
char arrayLeft[50];
char arrayRight[50];
int numLeft = 0;
int numRight = 0;
int bclocation = 0;
int i = 0;
if(g[0] == '(') {
i++;
}
if(g[0] == '-') {
i++;
if(g[1] == '(') {
i++;
}
}
int j = 0;
for(i; i < strlen(g); ++i) {
if(g[i] == '(') {
numLeft++;
} else if(g[i] == ')') {
numRight++;
}
arrayLeft[j] = g[i];
if(numRight == numLeft) {
if(g[i+1] == 'v' || g[i+1] == '>' || g[i+1] == '^') {
arrayLeft[j+1] = '\0';
bclocation = i+1;
binaryConnective = g[i+1];
break;
}
}
j++;
}
int m = 0;
int n = size(g) - 1;
if(g[strlen(g)-1] != ')') {
n++;
}
for(int k = bclocation+1; k < n; k++) {
arrayRight[m] = g[k];
m++;
}
arrayRight[m] = '\0';
char* leftSide = &arrayLeft[0];
char* rightSide = &arrayRight[0];
// printf("%s\n", leftSide);
// printf("%s\n", rightSide);
return rightSide;
}
char *firstexp(char *g) {
char* left = partone(g);
char leftArray[50];
int i = 0;
for(i; i < strlen(left); i++) {
leftArray[i] = left[i];
}
leftArray[i] = '\0';
char binConnective = bin(g);
int typeG = type(g);
if(typeG == 2) {
if(binConnective == '^') {
return &leftArray;
} else if(binConnective == '>') {
return &leftArray;
}
} else if(typeG == 3) {
if(binConnective == 'v')
return &leftArray;
}
char temp[50];
for(int i = 0; i < strlen(leftArray); i++) {
temp[i+1] = leftArray[i];
}
temp[0] = '-';
char* lefttwo = &temp[0];
if(typeG == 2) {
if(binConnective == 'v') {
return lefttwo;
}
} else if(typeG == 3) {
if(binConnective == '>' || binConnective == '^') {
return lefttwo;
}
}
return "Hello";
}
char *secondexp(char *g) {
// char binaryConnective = bin(g);
// char* right = parttwo(g);
// char rightArray[50];
// int i = 0;
// for(i; i< strlen(right); i++) {
// rightArray[i+1] = right[i];
// }
// rightArray[i] = '\0';
// int typeG = type(g);
// if(type(g) == 2) {
// if(binaryConnective == '^') {
// return &rightArray;
// }
// } else if(type(g) == 3) {
// if(binaryConnective == 'v' || binaryConnective == '>') {
// return &rightArray;
// }
// }
return "Hello";
}
typedef struct tableau tableau;
\
\
struct tableau {
char *root;
tableau *left;
tableau *right;
tableau *parent;
int closedbranch;
};
int closed(tableau *t) {
return 0;
}
void complete(tableau *t) {
}
/*int main(int argc, const char * argv[])
{
printf("Hello, World!\n");
printf("%d \n", parse("p^q"));
printf("%d \n", type("p^q"));
printf("%c \n", bin("p^q"));
printf("%s\n", partone("p^q"));
printf("%s\n", parttwo("p^q"));
printf("%s\n", firstexp("p^q"));
printf("Simulation complete");
return 0;
}*/
File 2:
#include <stdio.h>
#include <string.h> /* for all the new-fangled string functions */
#include <stdlib.h> /* malloc, free, rand */
#include "yourfile.h"
int Fsize = 50;
int main()
{ /*input a string and check if its a propositional formula */
char *name = malloc(Fsize);
printf("Enter a formula:");
scanf("%s", name);
int p=parse(name);
switch(p)
{case(0): printf("not a formula");break;
case(1): printf("a proposition");break;
case(2): printf("a negated formula");break;
case(3): printf("a binary formula");break;
default: printf("what the f***!");
}
printf("\n");
if (p==3)
{
printf("the first part is %s and the second part is %s", partone(name), parttwo(name));
printf(" the binary connective is %c \n", bin(name));
}
int t =type(name);
switch(t)
{case(0):printf("I told you, not a formula");break;
case(1): printf("A literal");break;
case(2): printf("An alpha formula, ");break;
case(3): printf("A beta formula, ");break;
case(4): printf("Double negation");break;
default: printf("SOmewthing's wrong");
}
if(t==2) printf("first expansion fmla is %s, second expansion fmla is %s\n", firstexp(name), secondexp(name));
if(t==3) printf("first expansion fmla is %s, second expansion fmla is %s\n", firstexp(name), secondexp(name));
tableau tab;
tab.root = name;
tab.left=0;
tab.parent=0;
tab.right=0;
tab.closedbranch=0;
complete(&tab);/*expand the root node then recursively expand any child nodes */
if (closed(&tab)) printf("%s is not satisfiable", name);
else printf("%s is satisfiable", name);
return(0);
}
If you look at the first file, you'll see a method called * firstexp(char * g).
This method runs perfectly, but only if another method called * secondexp(char * g) is commented out.
If * secondexp(char * g) is commented out, then *firstexp runs like this:
Enter a formula:((pvq)>-p)
a binary formula
the first part is (pvq) and the second part is -p the binary connective is >
A beta formula, first expansion fmla is -(pvq), second expansion fmla is Hello
((pvq)>-p) is satisfiableProgram ended with exit code: 0
otherwise, if *secondexp is not commented out, it runs like this:
Enter a formula:((pvq)>-p)
a binary formula
the first part is (pvq) and the second part is -p the binary connective is >
A beta formula, first expansion fmla is \240L, second expansion fmla is (-
((pvq)>-p) is satisfiable. Program ended with exit code: 0
As you can see, the outputs are completely different despite the same input. Can someone explain what's going on here?
In the commented-out parts of secondexp and in parttwo, you return the address of a local variable, which you shouldn't do.
You seem to fill a lot of ad-hoc sized auxiliary arrays. These have the problem that they might overflow for larger expressions and also that you cannot return them unless you allocate them on the heap with malloc, which also means that you have to free them later.
At first glance, the strings you want to return are substrings or slices of the expression string. That means that the data for these strings is already there.
You could (safely) return pointers into that string. That is what, for example strchr and strstr do. If you are willing to modify the original string, you could also place null terminators '\0' after substrings. That's what strtok does, and it has the disadvantage that you lose the information at that place: If you string is a*b and you modify it to a\0b, you will not know which operator there was.
Another method is to create a struct that stores a slice as pointer into the string and a length:
struct slice {
const char *p;
int length;
};
You can then safely return slices of the original string without needing to worry about additional memory.
You can also use the standard functions in most cases, if you stick to the strn variants. When you print a slice, you can do so by specifying a field width in printf formats:
printf("Second part: '%.*s'\n", s->length, s->p);
In your parttwo() function you return the address of a local variable
return rightSide;
where rightSide is a pointer to a local variable.
It appears that your compiler gave you a warning about this which you solved by making a pointer to the local variabe arrayRight, that may confuse the compiler but the result will be the same, the data in arrayRight will no longer exist after the function returns.
You are doing the same all over your code, and even worse, in the secondexp() function you return a the address of a local variable taking it's address, you are not only returning the address to a local variabel, but also with a type that is not compatible with the return type of the function.
This is one of many probable issues that your code may have, but you need to start fixing that to continue with other possible problems.
Note: enable extra warnings when compiler and listen to them, don't try to fool the compiler unless you know exactly what you're doing.

Resources