How to fix filling the struct with these data in c - c

I have struct input parameter and array of it called input_arr. I want to fill the array with the text as it gives the wrong value for the id and it work correctly with the name and nothing appear in visible.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct input_parameter {
int id;
char name[30];
int position;
char visible[5];
char required[5];
char parameter_type;
char client_id[5];
int min_length;
int max_length;
char confirm_required[5];
};
struct input_parameter input_arr[10];
char text[2*1024]="{\"success\": true,\"language\":
\"en\",\"action\":
\"GetServiceInputParameterList\",\"version\": 1,\"data\": {
\"input_parameter_list\": [{\"id\": 1489,\"service_id\":
12102,\"name\": \"Customer Number\",\"position\":
1,\"visible\":
true,\"required\": true,\"parameter_type\":
\"N\",\"client_id\":
true,\"min_length\": 11, \"max_length\":
11,\"confirm_required\":
false } ] }}";
Fill an array of structs with the text:
int main() {
int i = 0;
int Wstart = 0;
int Wend = 0;
char name[19] = {0x20};
char name1[19] = {0x20};
int menunum = 0;
int len = strlen(text);
while (1) // while ALL
{
if (i >= len) {
break;
}
if (text[i] == 'i' && text[i + 1] == 'd') {
while (1) { // while id
if (text[i] == ':') {
Wstart = i + 1;
Wend = 0;
i++;
} else if (text[i] == ',' || text[i] == '}') {
Wend = i;
strncpy(name, text + Wstart, Wend - Wstart);
input_arr[menunum].id = atoi(name);
memset(name, 0, sizeof(name));
i++;
break;
} else {
i = i + 1;
}
} // while id
} else if (text[i] == 'n' && text[i + 1] == 'a' && text[i + 2] == 'm' &&
text[i + 3] == 'e') {
while (1) { // while name
if (text[i] == ':') {
Wstart = i + 3;
Wend = 0;
i++;
} else if (text[i] == ',' || text[i] == '}') {
Wend = i - 1;
strncpy(name, text + Wstart, Wend - Wstart);
// name[Wend-Wstart] = '\0';
// memset(name1, 0, sizeof(name1));
if ((name[1] >= 'a' && name[1] <= 'z') ||
(name[1] >= 'A' && name[1] <= 'Z')) {
// printf("%c is an alphabet.",c);
strcpy(name1, name);
} else {
int vc = 0;
int ia = strlen(name) - 1;
for (ia = strlen(name) - 1; ia >= 0; ia--) {
name1[vc] = name[ia];
vc++;
}
}
strcpy(input_arr[menunum].name, name1);
menunum++;
memset(name, 0, sizeof(name));
i++;
break;
} else {
i = i + 1;
}
} // while name
} else if (text[i] == 'v' && text[i + 1] == 'i' && text[i + 2] == 's' &&
text[i + 3] == 'i' && text[i + 4] == 'b' &&
text[i + 5] == 'l' && text[i + 6] == 'e') {
while (1) { // while visible
if (text[i] == ':') {
Wstart = i + 3;
Wend = 0;
i++;
} else if (text[i] == ',' || text[i] == '}') {
Wend = i - 1;
strncpy(name, text + Wstart, Wend - Wstart);
// name[Wend-Wstart] = '\0';
memset(name1, 0, sizeof(name1));
if ((name[1] >= 'a' && name[1] <= 'z') ||
(name[1] >= 'A' && name[1] <= 'Z')) {
// printf("%c is an alphabet.",c);
strcpy(name1, name);
} else {
int vc = 0;
int ia = strlen(name) - 1;
for (ia = strlen(name) - 1; ia >= 0; ia--) {
name1[vc] = name[ia];
vc++;
}
}
strcpy(input_arr[menunum].visible, name1);
menunum++;
// memset(name, 0, sizeof(name));
i++;
break;
} else {
i = i + 1;
}
} // while visible
} else {
i++;
}
}
printf("id:%d \n name: %s \n visible: %s
\n",&input_arr[0].id,&input_arr[0].name,&input_arr[0].visible);
return 0;
}

Well you are printing address of id instead of its value using %d format specifier.
printf("id:%d\nname: %s\n visible: %d\n",&input_arr[0].id,&input_arr[0].name,&input_arr[0].visible);
should be
printf("id:%d \n name: %s \n visible: %d\n",input_arr[0].id,input_arr[0].name,input_arr[0].visible);

Related

My If-statements seem to be ignored even though my variables look fine in the debugger

I just started learning C (I'm an absolute beginner) and I'm trying to make a program that translates Roman numbers to Arabic and vice versa.
If I were to type "IX" my program should give me a "9" as an output but instead I get a "1". I tried to find the issue on my own using the debugger and I can see my program entering the first If-Statement
if (userString[localIndex] == 'I')
but then it skips the inner If-Statement
else if (userString[++localIndex] == 'X') {
ARABIC_NUM += 9;
localIndex++;
}
I'm not sure why this is happening. If I type "IV" my program outputs a "4" which is the correct answer but if I type "IVIV" my programs once again outputs a lonely "4" and ignores the rest of my input.
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdint.h>
#include <stdbool.h>
#include <string.h>
#define NOT_A_NUMBER 0
#define IS_ROMAN 1
#define IS_ARABIC 2
int ARABIC_NUM = 0;
int findStringLength(char* userString) {
int stringLength = 0;
size_t index = 0;
while (userString[index] != '\0')
{
if (userString[index] != '\0') {
stringLength++;
index++;
}
}
return stringLength;
}
void resetString(char* userString)
{
size_t stringLength = findStringLength(userString);
for (size_t index = 0; index < stringLength; index++)
{
userString[index] = '\0';
}
}
void printString(char* userString)
{
size_t stringLength = findStringLength(userString);
for (size_t index = 0; index < stringLength; index++)
{
if (userString[index] != '\0')
printf("~%zu:%c~ ", index, userString[index]);
else
printf("Null character");
}
}
bool ifEnd(char* numberInput, size_t counter) {
bool userEnd = false;
for (size_t index = 0; index < counter; index++)
{
if ((numberInput[index - 2] == 'E' && numberInput[index - 1] == 'N' && numberInput[index] == 'D')) {
userEnd = true;
}
}
return userEnd;
}
int isNumTrue(char userChar) {
int isRoman = NOT_A_NUMBER;
int isArabic = NOT_A_NUMBER;
if (userChar == 'I' || userChar == 'V' || userChar == 'X' ||
userChar == 'L' || userChar == 'C' || userChar == 'D' || userChar == 'M') {
isRoman = IS_ROMAN;
return isRoman;
}
else if (userChar == '0' || userChar == '1' || userChar == '2' || userChar == '3' || userChar == '4' || userChar == '5' || userChar == '6' || userChar == '7' || userChar == '8' || userChar == '9') {
isArabic = IS_ARABIC;
return isArabic;
}
else {
return NOT_A_NUMBER;
}
}
void convertToArabic(char* userString, size_t counter) {
for (size_t localIndex = 0; userString[localIndex] != '\0'; localIndex++) {
// printf("[ %c%s]", userString[localIndex], "-o ");
if (userString[localIndex] == 'I') {
if (userString[++localIndex] == 'V') {
printf("Made it in");
ARABIC_NUM += 4;
localIndex++;
}
else if (userString[++localIndex] == 'X') {
ARABIC_NUM += 9;
localIndex++;
}
else {
ARABIC_NUM += 1;
}
}
else if (userString[localIndex] == 'V') {
ARABIC_NUM += 5;
}
else if (userString[localIndex] == 'X') {
if (userString[localIndex++] == 'L') {
ARABIC_NUM += 40;
localIndex++;
}
else if (userString[localIndex++] == 'C') {
ARABIC_NUM += 90;
localIndex++;
}
else {
ARABIC_NUM += 10;
}
}
else if (userString[localIndex] == 'L') {
ARABIC_NUM += 50;
}
else if (userString[localIndex] == 'C') {
if (userString[localIndex++] == 'D') {
ARABIC_NUM += 400;
localIndex++;
}
else if (userString[localIndex++] == 'M') {
ARABIC_NUM += 900;
localIndex++;
}
else {
ARABIC_NUM += 100;
}
}
else if (userString[localIndex] == 'D') {
ARABIC_NUM += 500;
}
else if (userString[localIndex] == 'M') {
ARABIC_NUM += 1000;
}
else {
printf("Switch default. You shouldn't be seeing this");
}
/* else
{
printf("[ %c%s]", userString[localIndex],"-x ");
}*/
}
printf("%s%d%s", "\n Number was :", ARABIC_NUM, "\n");
}
bool convertToRoman(char* userString, char* romanStringHolder, size_t counter) {
bool isValid = true;
int arabicNum = atoi(userString);
char repetitionLimit = '\0';
for (size_t index = 0; arabicNum != 0; index++) {
/* if ((isNumTrue(userString[index]) == IS_ARABIC || userString[index] == '\n') && index < counter)
{
printf("[ %c%s]", userString[index], "-o ");
}*/
if (arabicNum >= 4000) {
do {
if (romanStringHolder[index - 2] == romanStringHolder[index - 1] == romanStringHolder[index]) {
repetitionLimit = romanStringHolder[index - 2];
}
if (arabicNum / 1000000 >= 1)//&& repetitionLimit != 'M')
{
romanStringHolder[index] = 'M';
arabicNum -= 1000000;
}
else if (arabicNum / 900000 >= 1)// && repetitionLimit != 'M')
{
romanStringHolder[index] = 'C';
romanStringHolder[++index] = 'M';
arabicNum -= 900000;
}
else if (arabicNum / 500000 >= 1)// && repetitionLimit != 'D')
{
romanStringHolder[index] = 'D';
arabicNum -= 500000;
}
else if (arabicNum / 400000 >= 1)//&& repetitionLimit != 'D')
{
romanStringHolder[index] = 'C';
romanStringHolder[++index] = 'D';
arabicNum -= 400000;
}
else if (arabicNum / 100000 >= 1)// && repetitionLimit != 'C')
{
romanStringHolder[index] = 'C';
arabicNum -= 100000;
}
else if (arabicNum / 90000 >= 1)//&& repetitionLimit != 'C')
{
romanStringHolder[index] = 'X';
romanStringHolder[++index] = 'C';
arabicNum -= 90000;
}
else if (arabicNum / 50000 >= 1)// && repetitionLimit != 'L')
{
romanStringHolder[index] = 'L';
arabicNum -= 50000;
}
else if (arabicNum / 40000 >= 1)// && repetitionLimit != 'L')
{
romanStringHolder[index] = 'X';
romanStringHolder[++index] = 'L';
arabicNum -= 40000;
}
else if (arabicNum / 10000 >= 1)//&& repetitionLimit != 'X')
{
romanStringHolder[index] = 'X';
arabicNum -= 10000;
}
else if (arabicNum / 9000 >= 1)// && repetitionLimit != 'X')
{
romanStringHolder[index] = 'I';
romanStringHolder[++index] = 'X';
arabicNum -= 9000;
}
else if (arabicNum / 5000 >= 1)//&& repetitionLimit != 'V')
{
romanStringHolder[index] = 'V';
arabicNum -= 5000;
}
else if (arabicNum / 4000 >= 1)//&& repetitionLimit != 'I')
{
romanStringHolder[index] = 'I';
romanStringHolder[++index] = 'V';
arabicNum -= 4000;
}
else if (arabicNum / 1000 >= 1)// && repetitionLimit != 'I')
{
romanStringHolder[index] = 'I';
arabicNum -= 1000;
}
index++;
} while (arabicNum >= 4000);
romanStringHolder[index] = '_';
index++;
}
if (arabicNum <= 3999) {
if (arabicNum / 1000 >= 1)
{
romanStringHolder[index] = 'M';
arabicNum -= 1000;
}
if (arabicNum / 900 >= 1)
{
romanStringHolder[index] = 'C';
romanStringHolder[++index] = 'M';
arabicNum -= 900;
}
else if (arabicNum / 500 >= 1)
{
romanStringHolder[index] = 'D';
arabicNum -= 500;
}
else if (arabicNum / 400 >= 1)
{
romanStringHolder[index] = 'C';
romanStringHolder[++index] = 'D';
arabicNum -= 400;
}
else if (arabicNum / 100 >= 1)
{
romanStringHolder[index] = 'C';
arabicNum -= 100;
}
else if (arabicNum / 90 >= 1)
{
romanStringHolder[index] = 'X';
romanStringHolder[++index] = 'C';
arabicNum -= 90;
}
else if (arabicNum / 50 >= 1)
{
romanStringHolder[index] = 'L';
arabicNum -= 50;
}
else if (arabicNum / 40 >= 1)
{
romanStringHolder[index] = 'X';
romanStringHolder[++index] = 'L';
arabicNum -= 40;
}
else if (arabicNum / 10 >= 1)
{
romanStringHolder[index] = 'X';
arabicNum -= 10;
}
else if (arabicNum / 9 >= 1)
{
romanStringHolder[index] = 'I';
romanStringHolder[++index] = 'X';
arabicNum -= 9;
}
else if (arabicNum / 5 >= 1)
{
romanStringHolder[index] = 'V';
arabicNum -= 5;
}
else if (arabicNum / 4 >= 1)
{
romanStringHolder[index] = 'I';
romanStringHolder[++index] = 'V';
arabicNum -= 4;
}
else if (arabicNum / 1 >= 1)
{
romanStringHolder[index] = 'I';
arabicNum -= 1;
}
}
}
if (romanStringHolder > 3999999)
printf("\n");
return isValid;
}
int findNumSystem(char* userString, char* toRomanString) {
//printf(" -%zu and %d-", counter, findStringLength(userString));
size_t counter = findStringLength(userString);
int romanNumAmount = 0;
int arabicNumAmount = 0;
int notNumAmount = 0;
for (size_t localIndex = 0; localIndex < counter; localIndex++) {
if (isNumTrue(userString[localIndex]) == IS_ROMAN || ((isNumTrue(userString[localIndex - 1]) == IS_ROMAN) && (userString[localIndex] == '\n')))
{
printf("[ %c%s]", userString[localIndex], "-R ");
romanNumAmount++;
if (romanNumAmount == (findStringLength(userString) - 1)) {
printf("\nAll Numbers are Roman");
convertToArabic(userString, counter);
break;
}
}
else if (isNumTrue(userString[localIndex]) == IS_ARABIC || ((isNumTrue(userString[localIndex - 1]) == IS_ARABIC) && (userString[localIndex] == '\n')))
{
printf("[ %c%s]", userString[localIndex], "-A ");
arabicNumAmount++;
if (arabicNumAmount == (findStringLength(userString) - 1))
{
printf("\nAll numbers are Arabic");
convertToRoman(userString, toRomanString, counter);
printString(toRomanString);
break;
}
}
else if (isNumTrue(userString[localIndex]) == NOT_A_NUMBER)
{
printf("[ %c%s]", userString[localIndex], "-X ");
notNumAmount++;
if (notNumAmount == (findStringLength(userString))) {
printf("\nNone of the characters is a number of either system");
}
}
}
}
#define LENGTH 1000u
int main() {
typedef char user_Input_Stream;
char lol = '\0';
user_Input_Stream arabToRomanString[LENGTH] = { '\0' };
user_Input_Stream numberInput[LENGTH] = { '\0' };
size_t counter = 0;
bool userEnd = false;
while ((lol != EOF) && (userEnd == false))
{
counter = 0;
printString(&numberInput);
resetString(&numberInput);
resetString(&arabToRomanString);
counter = 0;
printString(&numberInput);
ARABIC_NUM = 0;
printf("\n\n||Beta version, remember to not mix number systems yet||\n");
//Repeats until variable lol countains EOF or until boolean holds a true value
while ((lol != EOF) && (lol != '\n') && (userEnd == false))
{
//gets characters, assigns string with them. Gets rid of newline and stores string in array in uppercase
lol = getchar();
numberInput[counter] = toupper(lol);
userEnd = ifEnd(numberInput, counter);
counter++;
}
//TESTING Travels through String and outputs cells contents. Also, sets boolean to True if user writes END
for (size_t i = 0; i < counter; i++) {
if (numberInput[i] == '\n')
{
lol = '\\';
numberInput[i] = toupper(lol);
}
// printf("| [%zu] = %c |", i, numberInput[i]);
}
findNumSystem(numberInput, arabToRomanString);
printf("\n");
}
printf("\n");
return 0;
}
Does anyone have an idea of what the issue could be? (ARABIC_NUM is a global variable, the name is to make it easier for me to find for now.)
Just in case this might help somebody else, here's the solution I came up with using some of the pointers people in the comment section gave me. It was fairly simple:
I was under the impression that expressions within if-statements don't affect any variables they reference, but in reality they do.
For example: if(userString[localIndex] == 'I' && userString[localIndex++] == 'X')
In the line above, I was expecting the program to check both the current index and the next upcoming index, which it did but the expression userString[localIndex++] within the if-statement also permanently incremented my localIndex variable when I wasn't expecting that change to exist outside of the if-statement's parenthesis. So, my program would check the wrong indexes after the first comparison was made and thus why it gave me the wrong output.
To solve this, I created the variable nextIndex and used it to store the value localIndex +1 meaning it will always represent the index after localIndex. So, It now works as intended.
Below is what my program looks like now. (I moved around the if and if-else statements for better readability but the only changed that solved my predicament was the addition of nextIndex)
void convertToArabic(char* userString, size_t counter) {
size_t nextIndex = 0;
for (size_t localIndex = 0; localIndex < findStringLength(userString); localIndex++) {
// printf("[ %c%s]", userString[localIndex], "-o ");
nextIndex = localIndex+1;
if (userString[localIndex] == 'M') {
ARABIC_NUM += 1000;
}
else if (userString[localIndex] == 'C' && userString[nextIndex] == 'M') {
ARABIC_NUM += 900;
localIndex++;
}
else if (userString[localIndex] == 'D') {
ARABIC_NUM += 500;
}
else if (userString[localIndex] == 'C' && userString[nextIndex] == 'D') {
ARABIC_NUM += 400;
localIndex++;
}
else if(userString[localIndex] == 'C'){
ARABIC_NUM += 100;
}
else if (userString[localIndex] == 'X' && userString[nextIndex] == 'C') {
ARABIC_NUM += 90;
localIndex++;
}
else if (userString[localIndex] == 'L') {
ARABIC_NUM += 50;
}
else if (userString[localIndex] == 'X' && userString[nextIndex] == 'L'){
ARABIC_NUM += 40;
localIndex++;
}
else if (userString[localIndex] == 'X') {
ARABIC_NUM += 10;
}
else if ((userString[localIndex] == 'I') && (userString[nextIndex] == 'X')) {
//localIndex--;
ARABIC_NUM += 9;
localIndex++;
}
else if (userString[localIndex] == 'V') {
ARABIC_NUM += 5;
}
else if ((userString[localIndex] == 'I') && (userString[nextIndex] == 'V')) {
//localIndex--;
printf("Made it in");
ARABIC_NUM += 4;
localIndex++;
}
else if (userString[localIndex] == 'I') {
ARABIC_NUM += 1;
}
/* else
{
printf("[ %c%s]", userString[localIndex],"-x ");
}*/
}
printf("%s%d%s", "\n Number was :", ARABIC_NUM, "\n");
}

Find index of word in string

I want to write a function which will find index of word in string.
For example if string is
This is word.
my function for string "word" should return number 3.
Note: functions from string.h library and auxiliary strings are not allowed.
How could I do this in C?
I can't think of a solution better than this (though there might be better ones).
#include <stdio.h>
int main() {
char word[] = "This is a word";
int flag = 0, space = 0, pos = -1;
for (int i = 0; word[i] != '\0'; i++) {
if (flag == 1) {
break;
}
for (int j = 0; word[j] != '\0'; j++) {
if (flag == 1) {
break;
}
else if (word[j+1] == '\0' || word[j+2] == '\0' || word[j+3] == '\0') {
break;
}
else {
if (word[j] == 'w' && word[j+1] == 'o' && word[j+2] == 'r' && word[j+3] == 'd') {
flag = 1;
pos = j;
}
}
}
}
for (int i = 0; word[i] != '\0'; i++) {
if (word[i] == ' ' || word[i] == '!' || word[i] == '#') {// And many more symbols
fchars++;
}
else {
break;
}
}
if (flag == 1 && pos-1 > 0 && word[pos-1] == ' ') {
for (int i = 0; i < pos; i++) {
if (word[i] == ' ') {
space++;
}
}
printf("Found at position = %i\n", space+1-fchars);
}
else {
printf("Not found!\n");
}
}
You can split the sentence by space to get the words and then match each word in the sentence with the word you want to match
Please check this modified code:
#include<stdio.h>
int main()
{
char word[] = "word";
char string[100];
gets(string);
int curWordStart = -1;
int curWordEnd = -1;
int wordCount = 0;
int i = 0;
for (i = 0; string[i] != '\0'; i++)
{
if (string[i] == ' ')
{
int curWordLength = curWordEnd - curWordStart + 1;
if (curWordStart != -1 && curWordLength > 0)
{
wordCount++;
int foundMatch = 1;
int j;
int k = 0;
for (j = curWordStart; j <= curWordEnd; j++) {
if (word[k] == '\0') {
foundMatch = 0;
break;
}
if (word[k] != string[j])
{
foundMatch = 0;
break;
}
k++;
}
if (word[k] != '\0')
{
foundMatch = 0;
}
if (foundMatch == 1)
{
printf("%d\n", wordCount);
}
}
curWordStart = -1;
curWordEnd = -1;
}
else if ((string[i] >= 'a' && string[i] <= 'z') || (string[i] >= 'A' && string[i] <= 'Z'))
{
if (curWordStart == -1) {
curWordStart = i;
}
curWordEnd = i;
}
}
int curWordLength = curWordEnd - curWordStart + 1;
if (curWordStart != -1 && curWordLength > 0)
{
wordCount++;
int foundMatch = 1;
int j;
int k = 0;
for (j = curWordStart; j <= curWordEnd; j++) {
if (word[k] == '\0') {
foundMatch = 0;
break;
}
if (word[k] != string[j])
{
foundMatch = 0;
break;
}
k++;
}
if (word[k] != '\0')
{
foundMatch = 0;
}
if (foundMatch == 1)
{
printf("%d\n", wordCount);
}
}
return 0;
}
It will print each position of the searched word in the sentence. If you want to just print the first one, you can easily modify it.
Here are steps to follow:
you must specify precisely what is a word in the string.
measure the length len of the word to search
define an int index = 1
in a loop, using a pointer p starting at the beginning of the string:
advance p past all word delimiters (spaces, punctuation or non letters?)
if p is at end of string return 0 (not found).
measure the length len1 of the current word in the string
if len1 == len and all bytes are identical to those of the word, return index
otherwise skip the word by advancing p by len1, increment index and continue the loop.
Here is an implementation:
#include <stddef.h>
int isletter(char c) {
/* assuming ASCII */
return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z');
}
int word_index(const char *str, const char *word) {
const char *p = str;
size_t len, len1, i;
int index = 1;
for (len = 0; word[len]; len++)
continue;
for (;;) {
while (!is_letter(*p))
p++;
if (*p == '\0')
return 0;
for (len1 = 0; is_letter(p[len1]); len1++)
continue;
if (len1 == len) {
for (i = 0; i < len && p[i] == word[i]; i++)
continue;
if (i == len)
return index;
}
p += len1;
index++;
}
}

Movement for game character doesn't work at all

Here is the .c code from start to finish. I suspect it's an order of operations issue or something else.
The code is supposed to have a title screen where you can exit or play. If you hit play it renders a new char array in which you can move either left, right, or down (a/d/s). You get points for going down a row each time as well as going over 'P' spots on the array.
Once you hit y-coordinate 202 on the array as well as have positive points, you win and it renders a congrats char array. If you go negative in points (by hitting the '#' paces or the 'L' wall that goes down a row every 1/2 second) then you will lose and be told you lost in a new char array as well as be asked if you want to exit or play again.
And as mentioned before, the movement for the 'L's and the play character 'O' simply doesn't move.
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <fcntl.h>
#include <unistd.h>
char quickchar(float delay);
void render();
void titleRender();
void renderLoss();
void renderWin();
int score();
char titlescreen[20][59] = { };
char diffdiff[20][46] = {
(Grid removed due to char limit)
};
char gameover[20][50] = {
(Grid removed due to char limit)
};
char gameboard[203][26] = {
(Grid removed due to char limit)
};
int playerx;
int playery;
int pts;
void entryRender();
void gameRender();
int main() {
int input;
char replay;
int lx;
int ly;
char walkin;
int gaming;
char titlechoice;
int diff;
int running;
lx = 0;
ly = 0;
running = 1;
playerx = 13;
playery = 5;
pts = 25;
gaming = 0;
while (gaming == 0) {
titleRender();
printf("\033[1;32m");
printf("\nPress 'p' to play or 'x' to exit!");
printf("\033[0m");
scanf(" %c", &titlechoice);
if (titlechoice == 'p') {
gaming += 4;
}
if (titlechoice == 'x') {
return 0;
}
}
while (gaming == 4) {
system("stty -echo raw");
render();
printf("\033[1;35m");
printf("Choose a direction: s/Down, a/Left, d/Right.\n\r");
printf("\033[0m");
walkin = quickchar(0.5);
scanf("%c", &walkin);
//obj behaviour
if (walkin == 's' &&
gameboard[playery +1][playerx] != '#' &&
gameboard[playery + 1][playerx] != '+' &&
gameboard[playery + 1][playerx] != '|' &&
gameboard[playery + 1][playerx] != '-') {
playery++;
pts += 5;
if (gameboard[playery + 1][playerx] == '#') {
pts -= 25;
}
if (gameboard[playery + 1][playerx] == 'P') {
printf("Points increased!\n\r");
pts += 50;
gameboard[playery + 1][playerx] = '_';
}
}
else if (walkin == 'a' &&
gameboard[playery][playerx - 1] != '#' &&
gameboard[playery][playerx - 1] != '+' &&
gameboard[playery][playerx - 1] != '|' &&
gameboard[playery][playerx - 1] != '-') {
playerx--;
if (gameboard[playery][playerx - 1] == '#') {
pts -= 25;
}
if (gameboard[playery][playerx - 1] == 'P') {
printf("Points increased!\n\r");
pts += 50;
gameboard[playery][playerx - 1] = '_';
}
}
else if (walkin == 'd' &&
gameboard[playery][playerx + 1] != '#' &&
gameboard[playery][playerx + 1] != '+' &&
gameboard[playery][playerx + 1] != '|' &&
gameboard[playery][playerx + 1] != '-') {
playerx++;
if (gameboard[playery][playerx + 1] == '#') {
pts -= 25;
}
if (gameboard[playery + 1][playerx] == 'P) {
printf("Points increased!\n\r");
pts += 50;
gameboard[playery][playerx + 1] = '_';
}
}
if (walkin == 'a' || walkin == 's' || walkin == 'd' ||
walkin != 'a' || walkin != ' ' || walkin != 'd' ) {
for (ly = 0; ly = 202; ly++) {
for (lx = 1; lx = 25; lx++) {
gameboard[ly][lx] = 'L';
}
}
}
if (pts <= 0) {
system("clear");
renderLoss();
scanf("%c", replay);
if (replay == 'Y') {
gaming = 3;
}
if (replay == 'N') {
gaming = 5;
}
}
if (playery == 202) {
renderWin();
printf("");
printf("Congrats! You got a score of %d !", pts);
printf("");
scanf("%c", &replay);
if (replay == 'Y') {
gaming = 4;
}
if (replay == 'N') {
gaming = 5;
}
}
//player postion == 203y, then congrta screen
//ask player to set gaming to 4(replay) or none (exit program)
}
system("stty echo -raw");
return 0;
}
void render() {
int y,x,k;
system("clear");
printf("\033[01;33m");
printf("||POINTS: %d||\r\n", pts);
printf("\033[0m");
for (y = 0; y < 203; y++) {
for (x = 0; x < 26; x++) {
if (y == playery && x == playerx) {
printf("\033[0;32m");
printf("O");
printf("\033[0m");
}
else {
printf("\033[1;36m");
printf("%c", gameboard[y][x]);
printf("\033[0m");
}
}
printf("\r\n");
}
}
void titleRender() {
int y, x;
system("clear");
for (y = 0; y < 20; y++) {
for (x = 0; x < 59; x++) {
printf("\033[0;32m");
printf(" %c", titlescreen[y][x]);
printf("\033[0m");
}
printf("\r\n");
}
}
void renderLoss() {
int y, x;
system("clear");
for (y = 0; y < 26; y++) {
for (x = 0; x < 50; x++) {
printf("\033[0;31m");
printf(" %c", gameover[y][x]);
printf("\033[0m");
}
printf("\r\n");
}
}
void renderWin() {
int y, x;
system("clear");
for (y = 0; y < 20; y++) {
for (x = 0; x < 46; x++) {
printf("\033[0;33m");
printf(" %c", diffdiff);
printf("\033[0m");
}
printf("\r\n");
}
}
char quickchar(float delay) {
int flags;
char c;
usleep((int)(delay*1000000));
flags = fcntl(0, F_GETFL, 0);
fcntl(0, F_SETFL, flags | O_NONBLOCK);
c = getchar();
fcntl(0, F_SETFL, flags ^ O_NONBLOCK);
return c;
}

Counting the occurrence of words in a file

My wordOccurrences don't work if you read a file. They can appear twice in the counting so it doesn't count correctly but if I input from stdin it counts correctly.
So I have to read in a file (-i input.txt) count the words and word occurrences in that file. Output the results in the specific file that is given with -o output.txt. If there is a -c it should ignore punctuation and convert to lowercase
MAIN
#include "count.h"
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
//#include "wordOccurances.h"
#include "wordOccurrences.c"
int main(int argc, char **argv)
{
//Initialize variables
FILE *fi; // input file
FILE *fo =stdout; //output file
char buffer[1000];
char *input; //for manually entering string with -c
input = (char*)malloc(100 * sizeof(char));
char *name = "invalid";
int wordcount; // the number of words
char *ch; //a single character
ch = (char*)malloc(100000 * sizeof(char));
int c = 0, i, iFlag = 0, oFlag = 0, cFlag = 0;
char ptr1[50][100];
char *ptr;
if(argc == 1)
{
printf("Default settings\n");
}
else
{
for(i=1; i<argc;i++)
{
if(strcmp(argv[i], "-i")==0)
{
printf("input\n");
iFlag = 1;
fi = fopen(argv[++i],"r");
}
if(strcmp(argv[i], "-o")==0)
{
printf("output\n");
oFlag = 1;
fo = fopen(argv[++i],"w");
}
if(strcmp(argv[i], "-c")==0)
{
cFlag = 1;
}
}
}
if(iFlag ==1)
{
wordcount = countForFile(fi, wordcount);
fprintf(fo,"Word count is: %d \n", wordcount);
wordOccurencesForFile(fi, cFlag,fo);
}
else
{
printf("Enter text: ");
scanf(" %[^\n]s", input);
//Loop through input
int i = 0;
if(cFlag == 1)
{
int i =0;
for( i = 0;input[i]!='\0'; i++)
{
//find upperCase letters
if(input[i] >= 'A' && input[i] <= 'Z')
{
//overwrite to lowerCase
input[i] = tolower(input[i]);
//input[i] = input[i] +32;
}//end of if statement
//ignoring punctuation
if(input[i] == ',' || input[i] == '.' || input[i] == '!' || input[i] == '?' || input[i] == '"' || input[i] == ':' || input[i] ==';' || input[i] == '-')
{
input[i] = ' ';
}
} //end of for loop
}
wordcount = 0;
for(i = 0;input[i] != '\0'; i++)
{
if(input[i] == ' ' && input[i+1] != ' ')
wordcount++;
}// end of while loop
fprintf(fo,"WordCount is: %d\n", wordcount +1);
//count occurrences
wordOccurences(input, fo);
}
if(oFlag == 1)
{fclose(fo);}
}
wordOccurrences
/*
* C Program to Find the Frequency of Every Word in a
* given String
*/
#include <stdio.h>
#include <string.h>
#include "functions.h"
wordOccurences(char *input, FILE *output)
{
int count = 0, c = 0, i, j = 0, k, space = 0;
char str[100], p[50][100], str1[20], ptr1[50][100];
char *ptr;
// printf("Enter the string\n");
//scanf(" %[^\n]s", input);
printf("string length is %d\n", strlen(input));
for (i = 0;i<strlen(input);i++)
{
if ((input[i] == ' ')||(input[i] == ', ')||(input[i] == '.'))
{
space++;
}
}
for (i = 0, j = 0, k = 0;j < strlen(input);j++)
{
if ((input[j] == ' ')||(input[j] == 44)||(input[j] == 46))
{
p[i][k] = '\0';
i++;
k = 0;
}
else
p[i][k++] = input[j];
}
k = 0;
for (i = 0;i <= space;i++)
{
for (j = 0;j <= space;j++)
{
if (i == j)
{
strcpy(ptr1[k], p[i]);
k++;
count++;
break;
}
else
{
if (strcmp(ptr1[j], p[i]) != 0)
continue;
else
break;
}
}
}
for (i = 0;i < count;i++)
{
for (j = 0;j <= space;j++)
{
if (strcmp(ptr1[i], p[j]) == 0)
c++;
}
fprintf(output,"%s -> %d times\n", ptr1[i], c);
c = 0;
}
}
wordOccurencesForFile(FILE *fp, int cFlag, FILE *output)
{
fseek(fp, 0, SEEK_END);
long fsize = ftell(fp);
fseek(fp, 0, SEEK_SET);
char *str = (char*)malloc(fsize + 1);
fread(str, fsize, 1, fp);
fclose(fp);
str[fsize] = 0;
int count = 0, c = 0, i, j = 0, k, space = 0;
char p[1000][512], str1[512], ptr1[1000][512];
char *ptr;
if ( fp )
{
for (i = 0;i<strlen(str);i++)
{
if (cFlag == 1)
{
//ignoring punctuation
if(str[i] == ',' || str[i] == '.' || str[i] == '!'
|| str[i] == '?' || str[i] == '"' || str[i] == ':'
|| str[i] ==';' || str[i] == '-')
{
str[i] = ' ';
}
}
if ((str[i] == ' ')||(str[i] == ',')||(str[i] == '.'))
{
space++;
}
}
for (i = 0, j = 0, k = 0;j < strlen(str);j++)
{
if ((str[j] == ' ')||(str[j] == 44)||(str[j] == 46))
{
p[i][k] = '\0';
i++;
k = 0;
}
else
{
if (cFlag == 1)
{
//find upperCase letters
if(str[j] >= 'A' && str[j] <= 'Z')
{
//overwrite to lowerCase
str[j] = tolower(str[j]);
}//end of if statement
}
p[i][k++] = str[j];
}
}
k = 0;
for (i = 0;i <= space;i++)
{
for (j = 0;j <= space;j++)
{
if (i == j)
{
strcpy(ptr1[k], p[i]);
k++;
count++;
break;
}
else
{
if (strcmp(ptr1[j], p[i]) != 0)
continue;
else
break;
}
}
}
for (i = 0;i < count;i++)
{
for (j = 0;j <= space;j++)
{
if (strcmp(ptr1[i], p[j]) == 0)
c++;
}
fprintf(output,"%s %d \n", ptr1[i], c);
c = 0;
}
}
else
{
printf("Failed to open the file\n");
}
}

Validating input from Integers

Thank you guys for answering my first question, but I have another one. I have this code here
that uses strtol() function. It works, but the problem is that if I enter one of the three options: (d 2) its considered as a string, and if Input (2d) its a string, and (d2) is a string. Is there a way to detect the numbers within the array?
char userInput[256];
char *end;
printf("Please enter your name: ");
scanf("%s", userInput);
int userName = strtol(userInput, &end, 10);
if (!*end)
{
printf("You have enter an int");
}
else
{
printf("You have entered a string");
}
If you really just need to check to see if string has numbers in it, this will do:
int has_ints(char * str) {
const int len = strlen(str);
int i;
for (i = 0; i < len; i++) {
if (str[i] <= '9' && str[i] >= '0') {
return 1;
}
}
return 0;
}
I did this:) works quite beautifully!
int exit = 0;
int i;
while (exit != 1)
{
char userInput[256] = {0};
int asciiCode[256];
int zeroCounter = 0;
int letterProof = 0;
int numberProof = 0;
int specicalCharactersProof = 0;
printf("\nPlease enter your name: ");
fgets(userInput, 256, stdin);
for (i = 0; i < 256; i++)
{
asciiCode[i] = userInput[i];
if (asciiCode[i] == 0)
{
zeroCounter++;
}
}
int reSize = (256 - zeroCounter);
for (i = 0; i < reSize; i++)
{
if (asciiCode[i] >= '0' && asciiCode[i] <= '9')
{
numberProof = 1;
}
else if ((asciiCode[i] >= 'a' && asciiCode[i] <= 'z') || (asciiCode[i] >= 'A' && asciiCode[i] <= 'Z'))
{
letterProof = 1;
}
else if ((asciiCode[i] >= '!' && asciiCode[i] <= '/') || (asciiCode[i] >= ':' && asciiCode[i] <= '#') || (asciiCode[i] >= '[' && asciiCode[i] <= '`') || (asciiCode[i] >= '{' && asciiCode[i] <= '~'))
{
specicalCharactersProof = 3;
}
}
if (letterProof == 1 && numberProof == 0 && specicalCharactersProof == 0)
{
printf("\nWelcome %s\n", userInput);
exit = 1;
}
else
{
printf("\nInvalid Input.\n");
}
}
return(0);
}

Resources