testcase not running in c program - c

iam new to c program and facing difficulty in debugging programs.In the below code test case 2 is not running.I have found that the error is in reading interger n in the second test case.someone please hep me with this issue.Also please recommend me with some tools that can be ued for debugging c programs using terminal.Thanks for help
#include <stdio.h>
#include <stdlib.h>
int read(){
int r = 0;
char c = getchar_unlocked();
while(c >= '0' && c <= '9'){
r = r*10 + c - 48 ;
c = getchar_unlocked();
}
return r;
}
void main(){
int t = 0;
t = read();
int rr = 0;
for(rr = 0;rr < t;rr++){
int i,n = 0;
n = read();
int *p = (int *)calloc(n,sizeof(int));
for(i = 0;i < n;++i){
*(p+i) = getchar_unlocked() - 48;
}
int no,nz = 0;
for(i = 0;i < n;++i){
if(*(p+i) == 0){nz += 1;}
if(*(p+i) == 1){no += 1;}
}
int k = 0;
if(((no)%2 == 0) && ((nz)%2) == 0){
k = -1;
}
if(((no)%2 == 0) && ((nz)%2) == 1){
k = 0;
}
if(((no)%2 == 1) && ((nz)%2) == 0){
k = 1;
}
if(((no)%2 == 1) && ((nz)%2) == 1){
k = 1;
}
int result = 0;printf("%d\n",5556);
if(k == 1){
for(i = 0;i < n;++i){
if(*(p+i) == 1){
result = i+1 ;
break;
}
}
}
if(k == 0){
for(i = 0;i < n;++i){
if(*(p+i) == 0){
result = i+1 ;
break;
}
}
}
printf("%d\n",result);
}
}

Your strategy to read an integer is flawed. You don't have the logic to skip whitespaces. I would change the function name to read_int and change its implementation to
int read(){
int n;
if ( scanf("%d", &n) != 1 )
{
// Deal with the error
}
return n;
}
Also, change
*(p+i) = getchar_unlocked() - 48;
to
*(p+i) = read_int();
or a more intuitive version:
p[i] = read_int();
With those changes, I am able to read and process the numbers. But I still get the wrong output. I'll let you figure the logic error in your code.
Additional Comments
main is expected to return an int. If your compiler didn't complain about that, it's time to up the warning level. I use -Wall by default.
When you are in the process of debugging your code, it's always good to test the code that reads the input to make sure that there is no error in reading the input.
Here's what I did to your code:
#include <stdio.h>
#include <stdlib.h>
int read_int(){
int n;
if ( scanf("%d", &n) != 1 )
{
// Deal with the error.
}
return n;
}
int main(){
int t = 0;
int rr = 0;
t = read_int();
printf("t = %d\n", t);
for(rr = 0;rr < t;rr++){
int i,n = 0;
n = read_int();
printf("n = %d\n", n);
int *p = (int *)calloc(n,sizeof(int));
for(i = 0;i < n;++i){
p[i] = read_int();
printf("p[%d] = %d\n", i, p[i]);
}
int no,nz = 0;
for(i = 0;i < n;++i){
if(*(p+i) == 0){nz += 1;}
if(*(p+i) == 1){no += 1;}
}
int k = 0;
if(((no)%2 == 0) && ((nz)%2) == 0){
k = -1;
}
if(((no)%2 == 0) && ((nz)%2) == 1){
k = 0;
}
if(((no)%2 == 1) && ((nz)%2) == 0){
k = 1;
}
if(((no)%2 == 1) && ((nz)%2) == 1){
k = 1;
}
int result = 0;
// printf("%d\n",5556);
if(k == 1){
for(i = 0;i < n;++i){
if(*(p+i) == 1){
result = i+1 ;
break;
}
}
}
if(k == 0){
for(i = 0;i < n;++i){
if(*(p+i) == 0){
result = i+1 ;
break;
}
}
}
printf("%d\n",result);
}
return 0;
}

Related

My program gives the correct output in windows(gcc) but in Linux(gcc) it leads to segmentation fault

This program is to find the epsilon closure of all states of an NFA. I have used the stack to get this done.The program gives the right output when I compiled it using gcc and ran it Windows 10(Command Prompt). But when I compiled with the same compiler and ran it in Linux it results in segmentation fault. I have used any dynamic memory allocation for that matter.
I tried to debug using gdb but not able to find the problem. Detected a segmentation fault after a printf("\n") when displaying the transitions matrix.
It would be very helpful for someone could find the fault. Thanks in advance.
The input is read from a file : nfa.txt.
//states
q0 q1 q2
//input_symbols
0 1
//start_state
q0
//final_state
q2
//transitions of the form : intial_state input final_state
q0 0 q0
q0 e q1
q1 1 q1
q1 e q2
q2 2 q2
The output is as follows:
232 is to represent null transition(Φ) and -1 for ε.
States:
q0
q1
q2
Transitions read
232 0 1 2 -1
0 0 232 232 1
1 232 1 232 2
2 232 232 2 232
e-closure(0) : 0 1 2
e-closure(1) : 1 2
e-closure(2) : 2
Please bear with me because it's a fairly long program.
#include <stdio.h>
#include <string.h> //REMEMBER ME WHILE I'M GONE
#include <errno.h>
#include <stdlib.h>
FILE *file;
int numberOfStates = 0;
int flag = 0;
int states[20];
int j = 0;
int i = 0;
int k = 0;
char a[20];
int transitions[4][5];
int visited[10];
int MAXSIZE = 8;
int stack[8];
int top = -1;
int isempty()
{
if(top == -1)
return 1;
else
return 0;
}
int isfull()
{
if(top == MAXSIZE)
return 1;
else
return 0;
}
int pop()
{
int data;
if(!isempty()) {
data = stack[top];
top = top - 1;
return data;
}
else
printf("Could not retrieve data, Stack is empty.\n");
}
int push(int data) {
if(!isfull()) {
top = top + 1;
stack[top] = data;
}
else
printf("Could not insert data, Stack is full.\n");
}
int IsVisited(int edge)
{
for(int i = 0; i < 10; i++)
if(visited[edge] == 1)
return 1;
return 0;
}
void epsilon_closure(int state)
{
int e_closure[10];
for(int i = 0; i < 10; i++ )
{ e_closure[i] = -1;
visited[i] = 0;
}
push(state);
visited[state] = 1;
while(top != -1)
{
int u = pop();
j = 1;
while(j < 5)
{
//if there is an epsilon transition from the state 'u' to 'v'
if(transitions[j][0] == u && transitions[j][4] != 232) //ASCII of Φ = 232
{
if(! IsVisited(transitions[j][4]))
{
visited[transitions[j][4]] = 1;
push(transitions[j][4]);
}
}
j++;
}
}
j = 0;
for(int edge = 0; edge < 10; edge++)
{
if(visited[edge] == 1)
e_closure[j++] = edge;
}
printf("e-closure(%d) : ",state);
for (i = 0; e_closure[i] != -1; ++i)
printf("%d ", e_closure[i]);
printf("\n");
}
int main()
{
file = fopen("nfa.txt","r");
if (file == NULL) {
perror("fopen");
return -1;
}
//Reading the states
while(!feof(file))
{
fscanf(file,"%s",a);
if(strcmp("//states",a) == 0)
flag = 1;
else if(strcmp("//input_symbols",a) == 0)
break;
if (flag == 1 && a[0] != '/')
{
states[i++] = a[1] - '0';
}
numberOfStates = i;
}
//Display the states of the e-NFA
printf("\nStates : \n");
for(i = 0; i < numberOfStates; i++ )
{
printf("q%d\n",states[i]);
}
i = 1;
flag = 0;
//Reading the transition table
for(int i = 0; i < 4; i++){
for(int j = 0; j < 5; j++)
{
transitions[i][j] = 232;
}
}
while(!feof(file))
{
fgets(a,100,file);
if(a[0] == '/')
{
flag = 1;
}
if(flag == 1 && a[0] != '/')
{
j = 0;
//found a way to store the transition table in a matrix
if(a[3] == 'e')
transitions[(a[1] - '0') + 1][4] = a[6] - '0';
else
transitions[(a[1] - '0') + 1][(a[3] - '0') + 1] = a[6] - '0';
if(a[3] != 'e')
transitions[0][a[3] - '0' + 1] = a[3] - '0'; //input
else
transitions[0][4] = -1; // epsilon input
transitions[(a[1] - '0') + 1][0] = a[1] - '0'; //initial state
}
}
printf("\nTransitions read\n");
for(int i = 0; i < 4; i++){
for(int j = 0; j < 5; j++)
{
printf("%d\t",transitions[i][j]);
}
printf("\n"); //detected segmentation fault here
}
//Calling e-closure for all the states
for(k = 0; k < numberOfStates; k++)
{
epsilon_closure(states[k]);
}
return 0;
}
There is a bug here:
int push(int data) {
if(!isfull()) {
top = top + 1;
stack[top] = data;
}
else
printf("Could not insert data, Stack is full.\n");
}
If top == MAXSIZE-1, isfull() will return false, then you increment top to MAXSIZE and assign stack[MAXSIZE] what is out of bounds and invokes UB. Not having checked the complete source code, I could imagine that incrementing top after assigning would be correct or you have to change isfull() to return true if top >= MAXSIZE-1

C matrix character not appearing printing properly

I am trying to fill a char matrix in C and print it in C but I get only weird characters. I am running this programm on windows, hence the system(cls);
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void paint(char tab[10][10], int lignes, int colonnes)
{
system("cls");
for (int i = 0; i < lignes; i++)
{
for (int j = 0; j < colonnes; j++)
{
printf("%c", tab[i][j]);
}
printf("\n");
}
}
void create(char tab[10][10], int lignes, int colonnes)
{
for (int i = 0; i < lignes; i++)
{
for (int j = 0; j < colonnes; j++)
{
tab[i][j] = ' ';
if (i == 0 || i == lignes--)
tab[i][j] = 205;
if (j == 0 || j == colonnes--)
tab[i][j] = 186;
if (i == 0 && j == 0)
tab[i][j] = 201;
if (i == 0 && j == colonnes--)
tab[i][j] = 187;
if (i == lignes-- && j == 0)
tab[i][j] = 200;
if (i == lignes-- && j == colonnes--)
tab[i][j] = 188;
if (i == 50 && j == 50)
tab[i][j] = 248;
}
}
}
int main()
{
char tab[10][10];
create(tab, 10, 10);
paint(tab, 10, 10);
char i;
while(scanf(" %c", &i) != 'q')
{
}
}
I tried changing the output type in printf with %d and %s as shown in other answers here, but %d shows random numbers and %s makes the programm crash, I don't know if it is because of a segfault somewhere.I also tried using simple characters to fill my matrix, not their ascii value.
Don't mind the ineffective scanf , I am still trying to figure out keyboard input without using enter on my own for now.
there were a few problems with your code, like colonnes-- changes the value of colonnes while cheking your if statement
I believe you wanted to draw a rectangle
try this (it's your own code, modified a bit)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char tab[10][10];
void paint(int lignes, int colonnes)
{
system("cls");
for (int i = 0; i < lignes; i++)
{
for (int j = 0; j < colonnes; j++)
{
printf("%c", tab[i][j]);
}
printf("\n");
}
}
void create(int lignes, int colonnes)
{
for (int i = 0; i < lignes; i++)
{
for (int j = 0; j < colonnes; j++)
{
tab[i][j] = ' ';
if (i == 0 || i == lignes-1)
tab[i][j] = 205;
if (j == 0 || j == colonnes-1)
tab[i][j] = 186;
if (i == 0 && j == 0)
tab[i][j] = 201;
if (i == 0 && j == colonnes-1)
tab[i][j] = 187;
if (i == lignes-1 && j == 0)
tab[i][j] = 200;
if (i == lignes-1 && j == colonnes-1)
tab[i][j] = 188;
if (i == 50 && j == 50)
tab[i][j] = 248;
}
}
}
int main()
{
create(10, 10);
paint(10, 10);
}

Different output in Windows and Linux (gcc) C compilers

I have a program which solves maze, so that it finds possible route from Start(S) to Exit(E).Here is my Maze:
1111S11110
0000010001
110100010d
t001111110
0100000001
0111111101
1111111101
00000D01T1
0111110001
0000E01110
The possible route to it is :
Start S W W S S S E E E E E E S S S S W W N W W W W W W S S E E E E Exit
which is correct and i get it on CodeBlocks, However when i compile my code on dev through putty i get this:
Start S S S S S W N N W S W N N N W N Exit
Here is my whole code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
// Global Variables for use
int matrixSize,startX,startY,exitX,exitY;
char src[1500] = " ";
char Ndirection[50] = " N ";
char Sdirection[50] = " S ";
char Edirection[50] = " E ";
char Wdirection[50] = " W ";
// Function for finding the array length
int numOfLines(FILE *const mazeFile) {
int c, count;
count = 0;
for (;; ) {
c = fgetc(mazeFile);
if (c == EOF)
break;
if (c == '\n')
++count; // end of line => increment line counter
}
rewind(mazeFile);
return count+1;
}
int capLetter(char ch){
int result = 0;
if(ch >= 'A' && ch <= 'Z'){
result = 1;
}
return result;
}
int lowLetter(char ch){
int result = 0;
if(ch >= 'a' && ch <= 'z'){
result = 1;
}
return result;
}
int isSafe(char Mazearray[matrixSize][matrixSize],int x,int y){
if(x >= 0 && x < matrixSize && y >= 0 && y < matrixSize && Mazearray[x][y] != '1'){
return 1;
}
return 0;
}
void MazeSolution(char Mazearray[matrixSize][matrixSize],int x,int y,char pathArray[matrixSize][matrixSize],char wasHereArray[matrixSize][matrixSize]){
if(recursiveMaze(Mazearray,x,y,pathArray,wasHereArray) == 0){
printf("There does not exist a possible solution!!!");
}
else{
pathArray[startX][startY] = 'S';
}
}
int recursiveMaze(char Mazearray[matrixSize][matrixSize],int x,int y,char pathArray[matrixSize][matrixSize],char wasHereArray[matrixSize][matrixSize]){
if(x == startX && y == startY){
pathArray[x][y] = 'S';
}
if(x == exitX && y == exitY){
pathArray[x][y] = 'E';
return 1;
}
// check if the coordinate is safe to go(not 1)
if(isSafe(Mazearray,x,y) == 1 && wasHereArray[x][y] != '1'){
wasHereArray[x][y] = '1';
// Move North
if(recursiveMaze(Mazearray,x-1,y,pathArray,wasHereArray) == 1){
pathArray[x][y] = 'R';
strcat(src,Ndirection);
return 1;
}
// Move South
if(recursiveMaze(Mazearray,x+1,y,pathArray,wasHereArray) == 1){
pathArray[x][y] = 'R';
strcat(src,Sdirection);
return 1;
}
// Move East
if(recursiveMaze(Mazearray,x,y+1,pathArray,wasHereArray) == 1){
pathArray[x][y] = 'R';
strcat(src,Edirection);
return 1;
}
// Move West
if(recursiveMaze(Mazearray,x,y-1,pathArray,wasHereArray) == 1){
pathArray[x][y] = 'R';
strcat(src,Wdirection);
return 1;
}
}
return 0;
}
// Main Function
int main( int argc, char **argv )
{
// Opening the Matrix File
FILE *mazeFile;
mazeFile = fopen(argv[1], "r" );
if( mazeFile == NULL )
return 1;
matrixSize = numOfLines( mazeFile );
// Reading text file into 2D array
int i,j;
char mazeArray [matrixSize][matrixSize];
for (i = 0; i<matrixSize; i++) {
for (j = 0; j<matrixSize; j++) {
fscanf(mazeFile, "%c", &mazeArray[i][j]);
}
char eol;
fscanf(mazeFile, "%c", &eol);
}
// Variables
//Creating path array
char pathArray[matrixSize][matrixSize];
for (i = 0; i < matrixSize; i++){
for (j = 0; j < matrixSize; j++){
pathArray[i][j] = '0';
}
}
// CheckPoint array
char wasHereArray[matrixSize][matrixSize];
for (i = 0; i < matrixSize; i++){
for (j = 0; j < matrixSize; j++){
wasHereArray[i][j] = '0';
}
}
// Finding start and exit indexes
for (i = 0; i<matrixSize; i++) {
for (j = 0; j<matrixSize; j++) {
if(mazeArray[i][j] == 'S'){
startX = i;
startY = j;
}
if(mazeArray[i][j] == 'E'){
exitX = i;
exitY = j;
}
}
}
MazeSolution(mazeArray,startX,startY,pathArray,wasHereArray);
char *data = src;
int length=strlen(data);
char bytes[length];
int n=0;
while(n<=length)
{
bytes[n] = data[length-n-1];
n++;
}
FILE *f = fopen("path.txt", "w");
fprintf(f, "Start %s Exit",bytes);
fclose(mazeFile);
fclose(f);
return 0;
}
I don't know what is wrong and where to start?
DOS line endings are CR-LF ("\r\n") and *nix line endings are just LF ("\n"). Change these lines main:
char eol;
fscanf(mazeFile, "%c", &eol);
to:
int c = fgetc(mazefile); // Slurp a '\r' carriage return or '\n' linefeed character.
if ('\r' == c) {
c = fgetc(mazefile); // slurp the '\n' linefeed character.
}

Passing a string array to a function to be altered

so currently I am running a program to generate a bundle of files at random, then have them connect to each other, and create a maze like game.
I'm trying to build an array of the file paths to pass to a function so it can be generated then the array can be worked on some more by the calling function. What's happening is that is generating the array but leaving the first element(filepath[0]) blank thus seg. faulting on me. But when I set a breakpoint, all other sections of the array are fine, just not the first element. It's been about 9 months since I wrote and C and I'm unsure where my pointer hiccup is coming from, thank you all in advanced
Here is the code so far
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>
#include <time.h>
#include <stdbool.h>
void create_files(char (*filepath[7]));
int main(){
time_t t;
char *filepath[7];
srand((unsigned) time(&t));
int i = 0;
for (i = 0; i < 7; i++)
filepath[i] = malloc(60);
create_files(filepath);
for (i = 0; i < 7; i++)
free(filepath[i]);
return 0;
}
void create_files(char (*filepath[7])){
int i = 0, pid = getpid(),q = 0,random, r=7;
char procid[20];
sprintf(procid, "%d", pid);
char directory[80] = "./dringb.rooms.";
strcat(directory,procid);
int newdir = mkdir(directory, 0777);
for (q = 0; q < 7; q++)
filepath[q] = directory;
char *bigrooms[10] ={"/Bridge.txt","/Gate.txt","/Hallway.txt",
"/Dungeon.txt","/Galley.txt","/Throne.txt","/Boss.txt", "/Lab.txt",
"/Torture.txt", "/Courtyard.txt"};
bool redflag = false;
char *rooms[7];
q = 0;
while (q != 7){ //grabs the rooms at random from the set of bigrooms
random = rand()%10;
for(i = 0; i < 7; i++){
if (rooms[i] == bigrooms[random])
redflag = true;
}
if (redflag == false){
rooms[q] = bigrooms[random];
redflag = false;
q++;
}
else
redflag = false;
}
char **dest = (char **)malloc(r * sizeof(char *));
for (i=0; i<r; i++)
dest[i] = (char *)malloc(8 * sizeof(rooms)); //allocates each room a new space
for (i = 0; i < 7; i++){
strcat(dest[i], directory);
strcat(dest[i],rooms[i]);
filepath[i] = dest[i]; //creates directory path for each room.txt
}
int usedrooms[4];
for (i = 0; i < 7; i++){
FILE *f = fopen(filepath[i], "w");
fputs("Roomname: ", f);
fputs(rooms[i],f);
fputs("\n",f);
fclose(f);
}
for (i = 0; i < 7; i++){
FILE *f = fopen(filepath[i], "a+");
for (q = 0; q < 4; q++)
usedrooms[q] = 100;
int roomrand, q = 0, z = 0, connrooms = 3;
bool greenflag = true, retry = false;
roomrand = rand() %2;
if (roomrand == 1)
connrooms = 4;
while (q != connrooms){ //prevents from having a connection to same room
do{
retry = false;
roomrand = rand() % 7;
for(z = 0; z < 4; z++){
if (roomrand == usedrooms[z])
retry = true;
}
}while(roomrand == i || retry == true); //prevents from having a connection to same room
bool found = false;
char buffer[100];
rewind(f);
while(fscanf(f,"%s", buffer) == 1){
if (strcmp(buffer,rooms[roomrand]) == 0)//prevents a double connecting room from being added
greenflag = false;
}
if(greenflag == true){
usedrooms[q] = roomrand;
fputs("Connecting Room: ", f);
fputs(rooms[roomrand],f);
fputs("\n",f);
}
fclose(f);
greenflag = true;
found = false;
FILE *f2 = fopen(filepath[roomrand],"a+");
rewind(f2);
while(fscanf(f2,"%s", buffer) == 1){
if (strcmp(buffer,rooms[i]) == 0) //prevents a double connecting room from being added
found = true;
}
if (found == false){
fputs("Connecting Room: ",f2);
fputs(rooms[i],f2);
fputs("\n",f2);
}
fclose(f2);
fopen(filepath[i],"a+");
found = false;
q++;
}
q = 0;
fclose(f);
}
int usedroomtype[7];
int roomrand;
for (i = 0; i < 7; i++)
usedroomtype[i] = 100;
for (i = 0; i < 7;i++){
do{
redflag = false;
roomrand = rand() % 7;
for (q = 0; q < 7; q++)
if (roomrand == usedroomtype[q])
redflag = true;
} while (redflag == true);
usedroomtype[i] = roomrand;
FILE *fp = fopen(filepath[roomrand], "a+");
if (i == 0)
fputs("Room Type: Start Room", fp);
else if (i == 6)
fputs("Room Type: End Room",fp);
else
fputs ("Room Type: Mid Room",fp);
fclose(fp);
}
}
The array is being passed correctly. The problem is that data is getting corrupted.
for (q = 0; q < 7; q++)
filepath[q] = directory;
This is invalid. It should be strcpy(filepath[q], directory); It's okay to set for example char *temp = filepath[q], because temp was not allocated. But filepath[q] is already allocated. Use strcpy to to change it value.
Later there is a similar error
char **dest = (char **)malloc(r * sizeof(char *));
for (i=0; i<r; i++)
dest[i] = (char *)malloc(8 * sizeof(rooms));
for (i = 0; i < 7; i++){
strcat(dest[i], directory);
strcat(dest[i],rooms[i]);
filepath[i] = dest[i]; //creates directory path for each room.txt
}
Two things. First, dest is not initialized. Always start with strcpy with uninitialized string, then use strcat. Second, use strcpy to change the value of filepath[i] as explained earlier. dest is actually not needed. You could just copy directly to filepath
for (i = 0; i < 7; i++)
{
strcpy(filepath[i], directory);
strcat(filepath[i], rooms[i]);
}
As mentioned in comments, allocation for filepath should be larger. directory is max 80 bytes, room is max 10 bytes, so filepath should be max 90 bytes.
for (i = 0; i < 7; i++)
filepath[i] = malloc(90);
Also some values are not initialized, example char *rooms[7];
Elsewhere:
int pid = getpid();
char procid[20];
sprintf(procid, "%d", pid);
char directory[80] = "./dringb.rooms.";
strcat(directory,procid);
You are already using sprintf, you can simplify this as follows:
sprintf(directory, "./dringb.rooms.%d", getpid());
Example:
int main()
{
time_t t;
srand((unsigned) time(&t));
char *filepath[7];
int i = 0;
for (i = 0; i < 7; i++)
filepath[i] = malloc(90);
create_files(filepath);
for (i = 0; i < 7; i++)
printf("%s\n", filepath[i]);
for (i = 0; i < 7; i++)
free(filepath[i]);
return 0;
}
void create_files(char *filepath[7])
{
int i = 0, random;
char directory[80];
sprintf(directory, "./dringb.rooms.%d", getpid());
//mkdir(directory);
mkdir(directory, 0777);
int q;
for (q = 0; q < 7; q++) strcpy(filepath[q], directory);
char *bigrooms[20] ={"/Bridge.txt","/Gate.txt","/Hallway.txt","/Dungeon.txt","/Galley.txt","/Throne.txt","/Boss.txt", "/Lab.txt","/Torture.txt", "/Courtyard.txt"};
bool redflag = false;
char *rooms[7];
for (i = 0; i < 7; i++) rooms[i] = 0;
q = 0;
while (q != 7)
{
//grabs the rooms at random from the set of bigrooms
random = rand()%10;
for(i = 0; i < 7; i++)
{
if (rooms[i] == bigrooms[random])
redflag = true;
}
if (redflag == false)
{
rooms[q] = bigrooms[random];
redflag = false;
q++;
}
else
redflag = false;
}
for (i = 0; i < 7; i++)
{
strcpy(filepath[i], directory);
strcat(filepath[i], rooms[i]);
}
int usedrooms[4];
for (i = 0; i < 7; i++)
{
FILE *f = fopen(filepath[i], "w");
fputs("Roomname: ", f);
fputs(rooms[i],f);
fputs("\n",f);
fclose(f);
}
for (i = 0; i < 7; i++)
{
FILE *f = fopen(filepath[i], "a+");
for (q = 0; q < 4; q++)
usedrooms[q] = 100;
int roomrand, q = 0, z = 0, connrooms = 3;
bool greenflag = true, retry = false;
roomrand = rand() %2;
if (roomrand == 1)
connrooms = 4;
while (q != connrooms)
{ //prevents from having a connection to same room
do
{
retry = false;
roomrand = rand() % 7;
for(z = 0; z < 4; z++)
{
if (roomrand == usedrooms[z])
retry = true;
}
}
while(roomrand == i || retry == true); //prevents from having a connection to same room
bool found = false;
char buffer[100];
rewind(f);
while(fscanf(f,"%s", buffer) == 1)
{
if (strcmp(buffer,rooms[roomrand]) == 0)//prevents a double connecting room from being added
greenflag = false;
}
if(greenflag == true)
{
usedrooms[q] = roomrand;
fputs("Connecting Room: ", f);
fputs(rooms[roomrand],f);
fputs("\n",f);
}
fclose(f);
greenflag = true;
found = false;
FILE *f2 = fopen(filepath[roomrand],"a+");
rewind(f2);
while(fscanf(f2,"%s", buffer) == 1)
{
if (strcmp(buffer,rooms[i]) == 0) //prevents a double connecting room from being added
found = true;
}
if (found == false)
{
fputs("Connecting Room: ",f2);
fputs(rooms[i],f2);
fputs("\n",f2);
}
fclose(f2);
fopen(filepath[i],"a+");
found = false;
q++;
}
q = 0;
fclose(f);
}
int usedroomtype[7];
int roomrand;
for (i = 0; i < 7; i++)
usedroomtype[i] = 100;
for (i = 0; i < 7; i++)
{
do
{
redflag = false;
roomrand = rand() % 7;
for (q = 0; q < 7; q++)
if (roomrand == usedroomtype[q])
redflag = true;
}
while (redflag == true);
usedroomtype[i] = roomrand;
FILE *fp = fopen(filepath[roomrand], "a+");
if (i == 0)
fputs("Room Type: Start Room", fp);
else if (i == 6)
fputs("Room Type: End Room",fp);
else
fputs ("Room Type: Mid Room",fp);
fclose(fp);
}
}

Acquisition of string c

This is the code of a simple code of game of anagram:
#define NP 5
#define LP 10
void anagrammi() {
srand(time (NULL));
char words[NP][LP] = {"cane", "gatto", "gallo", "rana", "ibis"};
typedef struct {
char parola[LP];
int usati[LP];
char anagramma[LP];
}an ;
int a, len, i, j, cont;
char merda[LP], c;
an yoda;
a = rand()%5;
strcpy(yoda.parola, words[a]);
len = strlen(yoda.parola);
for (i = 0; i < len; i++){
yoda.usati[i] = len+2;
}
i = 0;
while (i < len){
cont = 0;
a = rand()%len;
for (j = 0; j < len; j++){
if (a == yoda.usati[j]) cont++;
} if (cont == 0) {
yoda.usati[i] = a;
yoda.anagramma[i] = yoda.parola[a];
i++;
}
}
j = 0;
cont = 0;
yoda.anagramma[i] = '\0';
printf("Anagramma di %s ? ", yoda.anagramma);
c = getchar() ;
while( c != '\n' && j < LP ){
merda[j] = c ;
j++ ;
c = getchar(); }
merda[j] = '\0';
for (i = 0; i < len; i++){
if (merda[i] =! yoda.parola[i]) cont++;
printf("\n%d", cont);
printf("\n%c", merda[i]);
printf("\n%c", yoda.parola[i]);
}
if (cont =! 0) printf("\nFALSE");
else printf ("\nTRUE");
}
The program goes, but when I insert the word and compare this to the original word, the final output is always FALSE, even if I put the right word. The problem occurs also without \0.Can anyone give me a hand?
Thanks to the answer, this is the perfectly working programm:
void anagrammi() {
srand(time (NULL));
char words[NP][LP] = {"cane", "gatto", "gallo", "rana", "ibis"};
typedef struct {
char parola[LP];
int usati[LP];
char anagramma[LP];
}an ;
int a, len, i, j, cont;
char merda[LP], c;
an yoda;
a = rand()%5;
strcpy(yoda.parola, words[a]);
len = strlen(yoda.parola);
for (i = 0; i < len; i++){
yoda.usati[i] = len+2;
}
i = 0;
while (i < len){
cont = 0;
a = rand()%len;
for (j = 0; j < len; j++){
if (a == yoda.usati[j]) cont++;
} if (cont == 0) {
yoda.usati[i] = a;
yoda.anagramma[i] = yoda.parola[a];
i++;
}
}
j = 0;
cont = 0;
yoda.anagramma[i] = '\0';
printf("Anagramma di %s ? ", yoda.anagramma);
c = getchar() ;
while( c != '\n' && j < LP ){
merda[j] = c ;
j++ ;
c = getchar(); }
for (i = 0; i < len; i++){
if (merda[i] != yoda.parola[i]) cont++;
}
i = strlen(merda);
if (cont != 0 || i > len ) printf("\nNON HAI INDOVINATO");
else printf ("\nHAI INDOVINATO");
}
(cont =! 0) that should be (cont != 0)
– kaylum

Resources