GPRMC string is not showing after extracting the data - C - c

Im working around PIC with GPS module. My GPS modules send NMEA data
$GPRMC,000036.799,V,,,,,0.00,0.00,060180,,,N*40
$GPVTG,0.00,T,,M,0.00,N,0.00,K,N*32
$GPGGA,000036.799,,,,,0,0,,,M,,M,,*4A
$GPGSA,A,1,,,,,,,,,,,,,,,*1E
$GPGSV,1,1,00*79
$GPGLL,,,,,000036.799,V,N*78
$GPTXT,01,01,02,ANTSTATUS=OPEN*2B
Here my intention is to extract "GPRMC" data string from the above. I think i've sucessfully took it off the "GPRMC", but the problem is the exracted data string doesnt have GPRMC string. here is the screenshot of my hyperterminal window
Here is my code:
while (1)
{
//memset(gpsdata,0,sizeof(gpsdata));
char c = uartrec2();
if (c == '$')
{
char c1 = uartrec2();
if (c1 == 'G')
{
char c2 = uartrec2();
if (c2 == 'P')
{
char c3 = uartrec2();
if (c3 == 'R')
{
char c4 = uartrec2();
if (c4 == 'M')
{
char c5 = uartrec2();
if (c5 == 'C')
{
for (i = 0 ; i < 100 ; i++)
{
gpsdata[i] = uartrec2();
/* while (gpsdata[i] == '\r' || gpsdata[i] == '\n')
{
break;
} */
if (gpsdata[i] == '\r' ) // Checking for '\r'
{
gpsdata[i] = '\0';
}
}
}
}
}
else
{
printf("Bad GPS data");
}
}
}
}
uart_str(gpsdata);
uart_str("\r\n");
}

The first thing you should do is try to figure out a better way to write this program, this could be
int done;
done = 0;
while (done == 0)
{
const char *string;
int valid;
valid = 1;
string = "$GPRMC";
while ((*string != '\0') && ((valid = (uartec2() == *string)) != 0))
string++;
if (valid != 0)
{
for (int i = 0 ; i < 100 ; ++i)
{
gpsdata[i] = uartec2();
if (gpsdata[i] != '\r')
continue;
gpsdata[i] = '\0';
}
uart_str(gpsdata);
uart_str("\r\n");
}
}

How about just adding it since you know there was it?
if (c5 == 'C')
{
gpsdata[0] = '$';
gpsdata[1] = 'G';
gpsdata[2] = 'P';
gpsdata[3] = 'R';
gpsdata[4] = 'M';
gpsdata[5] = 'C';
for (i = 6 ; i < 100 ; i++)
{
gpsdata[i] = uartrec2();
/* while (gpsdata[i] == '\r' || gpsdata[i] == '\n')
{
break;
} */
if (gpsdata[i] == '\r' ) // Checking for '\r'
{
gpsdata[i] = '\0';
}
}
}

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;
}

C Battleship Game Linked List print_node function

I've been working on a battleship program in C for a class and I am having trouble with my print_node function returning the values from my head node (currentState, ship_type, charInput etc.). Each time I run it, it compiles however it always outputs "0". I'm hoping a second set of eyes could help me figure this out. Thank you, and forgive me for the messy code.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <stdbool.h>
#include <time.h>
#define SIZE 10
typedef struct Node{
char currentState;
char ship_type[20];
char charInput;
int intInput;
struct Node* next;
}Node;
char** initialization(){
int i, j, k, row, col;
char **board = (char**)malloc(sizeof(char*)*SIZE);
for (i = 0; i < SIZE; i++){
board[i] = (char*)malloc(sizeof(char)*SIZE);
}
for(i = 0; i < SIZE; i++){
for(j = 0; j < SIZE; j++){
board[i][j] = '-';
}
}
//place the first ship
//the direction of placement is hard coded
//you can change it if you want
bool placed1 = false;
while(placed1 == false){
row = rand()%10;
col = rand()%10;
if(row+1 < 10 && row-1 >= 0){
if((board[row][col] = '-') &&
(board[row+1][col] = '-')){
board[row][col] = 'D';
board[row+1][col] = 'D';
placed1 = true;
}
else if((board[row][col] == '-') &&
(board[row-1][col] == '-')){
board[row][col] = 'D';
board[row-1][col] = 'D';
placed1 = true;
}
}
}
//place the second ship
bool placed2 = false;
while (placed2 == false){
row = rand()%10;
col = rand()%10;
if((row+1 < 10 && row+2 < 10) &&
(row-1 >= 0 && row-2 >= 0) &&
(col+1 < 10 && col+2 < 10) &&
(col-1 >= 0 && col-2 >= 0)){
if((board[row][col] == '-') &&
(board[row][col+1] == '-') &&
(board[row][col+2] == '-')){
board[row][col] = 'C';
board[row][col+1] = 'C';
board[row][col+2] = 'C';
placed2 = true;
}
else if((board[row][col] == '-') &&
(board[row][col-1] == '-') &&
(board[row][col-2] == '-')){
board[row][col] = 'C';
board[row][col-1] = 'C';
board[row][col-2] = 'C';
placed2 = true;
}
else if((board[row][col] == '-') &&
(board[row+1][col] == '-') &&
(board[row+2][col] == '-')){
board[row][col] = 'C';
board[row+1][col] = 'C';
board[row+2][col] = 'C';
placed2 = true;
}
else if((board[row][col] == '-') &&
(board[row-1][col] == '-') &&
(board[row-2][col] == '-')){
board[row][col] = 'C';
board[row-1][col] = 'C';
board[row-2][col] = 'C';
placed2 = true;
}
}
}
//place the third ship
bool placed3 = false;
while (placed3 == false){
row = rand()%10;
col = rand()%10;
if((row+1 < 10 && row+2 < 10) &&
(row-1 >= 0 && row-2 >= 0) &&
(col+1 < 10 && col+2 < 10) &&
(col-1 >= 0 && col-2 >= 0)){
if((board[row][col] == '-') &&
(board[row][col+1] == '-') &&
(board[row][col+2] == '-')){
board[row][col] = 'S';
board[row][col+1] = 'S';
board[row][col+2] = 'S';
placed3 = true;
}
else if((board[row][col] == '-') &&
(board[row][col-1] == '-') &&
(board[row][col-2] == '-')){
board[row][col] = 'S';
board[row][col-1] = 'S';
board[row][col-2] = 'S';
placed3 = true;
}
else if((board[row][col] =='-') &&
(board[row+1][col] == '-') &&
(board[row+2][col] == '-')){
board[row][col] = 'S';
board[row+1][col] = 'S';
board[row+2][col] = 'S';
placed3 = true;
}
else if((board[row][col] == '-') &&
(board[row-1][col] == '-') &&
(board[row-2][col] == '-')){
board[row][col] = 'S';
board[row-1][col] = 'S';
board[row-2][col] = 'S';
placed3 = true;
}
}
}
bool placed4 = false;
while (placed4 == false){
row = rand()%10;
col = rand()%10;
if((row+1 < 10 && row+2 < 10 && row+3 < 10) &&
(row-1 >= 0 && row-2 >= 0 && row-3 >= 0) &&
(col+1 < 10 && col+2 < 10 && col+3 < 10) &&
(col-1 >= 0 && col-2 >= 0 && col-3 >= 0)){
if((board[row][col] == '-') &&
(board[row+1][col] == '-') &&
(board[row+2][col] == '-') &&
(board[row+3][col] == '-')){
board[row][col] = 'B';
board[row+1][col] = 'B';
board[row+2][col] = 'B';
board[row+3][col] = 'B';
placed4 = true;
}
else if((board[row][col] == '-') &&
(board[row-1][col] == '-') &&
(board[row-2][col] == '-') &&
(board[row-3][col] == '-')){
board[row][col] = 'B';
board[row-1][col] = 'B';
board[row-2][col] = 'B';
board[row-3][col] = 'B';
placed4 = true;
}
else if((board[row][col] == '-') &&
(board[row][col+1] == '-') &&
(board[row][col+2] == '-') &&
(board[row][col+3] == '-')){
board[row][col] = 'B';
board[row][col+1] = 'B';
board[row][col+2] = 'B';
board[row][col+3] = 'B';
placed4 = true;
}
else if((board[row][col] == '-') &&
(board[row][col-1] == '-') &&
(board[row][col-2] == '-') &&
(board[row][col-3] == '-')){
board[row][col] = 'B';
board[row][col-1] = 'B';
board[row][col-2] = 'B';
board[row][col-3] = 'B';
placed4 = true;
}
}
}
bool placed5 = false;
while (placed5 == false){
row = rand()%10;
col = rand()%10;
if((row+1 < 10 && row+2 < 10 && row+3 < 10 && row+4 < 10) &&
(row-1 >= 0 && row-2 >= 0 && row-3 >= 0 && row-4 >= 0) &&
(col+1 < 10 && col+2 < 10 && col+3 < 10 && col+4 < 10) &&
(col-1 >= 0 && col-2 >= 0 && col-3 >= 0 && col-4 >= 0)){
if((board[row][col] == '-') &&
(board[row+1][col] == '-') &&
(board[row+2][col] == '-') &&
(board[row+3][col] == '-') &&
(board[row+4][col] == '-')){
board[row][col] = 'R';
board[row+1][col] = 'R';
board[row+2][col] = 'R';
board[row+3][col] = 'R';
board[row+4][col] = 'R';
placed5 = true;
}
else if((board[row][col] == '-') &&
(board[row-1][col] == '-') &&
(board[row-2][col] == '-') &&
(board[row-3][col] == '-') &&
(board[row-4][col] == '-')){
board[row][col] = 'R';
board[row-1][col] = 'R';
board[row-2][col] = 'R';
board[row-3][col] = 'R';
board[row-4][col] = 'R';
placed5 = true;
}
else if((board[row][col] == '-') &&
(board[row][col+1] == '-') &&
(board[row][col+2] == '-') &&
(board[row][col+3] == '-') &&
(board[row][col+4] == '-')){
board[row][col] = 'R';
board[row][col+1] = 'R';
board[row][col+2] = 'R';
board[row][col+3] = 'R';
board[row][col+4] = 'R';
placed5 = true;
}
else if((board[row][col] == '-') &&
(board[row][col-1] == '-') &&
(board[row][col-2] == '-') &&
(board[row][col-3] == '-') &&
(board[row][col-4] == '-')){
board[row][col] = 'R';
board[row][col-1] = 'R';
board[row][col-2] = 'R';
board[row][col-3] = 'R';
board[row][col-4] = 'R';
placed5 = true;
}
}
}
return board;
}
void update_state(char* state, char ** board, char character, int col){
int row;
char shipType[20];
row = character % 65;
if(board[row][col] == '-'){
strcpy(state, "MISS");
}
else{
strcpy(state, "HIT!");
/* add code to change the board to indicate
* that shot hit , for example you could change
* the corresponding letter back to '-'.
* but before this, you need to record the letter
* and corresponding ship type.
*/ //COMPLETED
char shipChar = board[row][col];
if(shipChar == 'R'){
strcpy(shipType,"Carrier");
printf("%s", shipType);
}
else if(shipChar == 'B'){
strcpy(shipType,"Battleship");
printf("%s", shipType);
}
else if(shipChar == 'S'){
strcpy(shipType,"Submarine");
printf("%s", shipType);
}
else if(shipChar == 'C'){
strcpy(shipType,"Cruiser");
printf("%s", shipType);
}
else if(shipChar == 'D'){
strcpy(shipType,"Destroyer");
printf("%s", shipType);
}
printf("%c", shipChar);
board[row][col] = '-'; //set target coordinates to '-'
}
/* add code to update temp node's attributes (i.e
* hit or miss, ship type, then insert the temp node
* the node into the linked list.
* You may need to write the insert node function
* (you can refer to the insert node function in lab5
* handout )
*/
struct Node *head, *tail;
head = tail = NULL;
insert_node(&head, &tail, col, row, *state, shipType);
print_node(head);
//check if game is over //completed
int m = 0;
int k, l;
for(k = 0; k < SIZE; k++){
for(l = 0; l < SIZE; l++){
if(board[k][l] == '-'){
m++;
if(m >= 100){
strcpy(state, "GAME OVER!");
}
}
}
}
}
int accept_input(char * c, int * i){
bool flag = true;
do{
printf("Enter a letter A-J and number 0-9 ex. B4 - enter Z0 to end\n");
int size = scanf(" %c%d", c, i);
if(size != 2){
printf("INVALID INPUT\n");
continue;
}
*c = toupper(*c);
if(*c == 'Z' && *i == 0)
break;
if (*c < 65 || *c > 74)
printf("INVALID INPUT\n");
else if (*i <0 || *i >9)
printf("INVALID INPUT\n");
else
flag = false;
}while(flag);
}
/*
char currentState;
char ship_type;
*/
void insert_node(struct Node **h, struct Node **t, int x, char y, char* state, char shipTyp){
//create new node with value given by int x, y
struct Node *temp;
if ((temp = (struct Node *)malloc(sizeof(struct Node))) == NULL){
printf("Node Allocation Failed \n");
exit(1);
}
//space for node obtained, copy values into node
temp->charInput = y; //store user character input
temp->intInput = x; //store user number input
temp->currentState = state; //store state
temp->ship_type[20] = shipTyp; //store shipType
temp->next = NULL;
if (*h == NULL){
//list is empty if so
*h = *t = temp;
}
else{ //list isnt empty, use *t to add node at the end
(*t)->next = temp;
*t = (*t)->next;
}
}
//will be converted to a write to file function
void print_node(struct Node *h){
if(h == NULL){
printf("The list is empty.\n");
}
else{
printf("Values in the list are: \n");
while(h != NULL) {
printf("%c\n", h->charInput);
printf("%s\n", h->ship_type);
h = h->next;
}
}
}
void display_state(char* state, char** board){
int i, j;
printf("\n**** %s ****\n", state);
printf(" 0 1 2 3 4 5 6 7 8 9\n");
for (i = 0; i < SIZE; i++){
printf("%c ", 65+i);
for (j = 0; j < SIZE; j++){
printf("%c ", board[i][j]);
}
printf("\n");
}
}
int teardown(char ** board){
int i;
for(i = 0; i < SIZE; i++)
free(board[i]);
free(board);
/* add code below to traverse the linkded list
* you should create a log file name "log.txt"
* traverse each node in the linked list, and
* write the information in each node into "log.txt"
* Each line should follow this format:
* Fired at A1. Hit - Carrier.
* Fired at C2. Miss.
* You may refer to the print_list function in lab5
* handout.
* In addition, remember to free the nodes of the
* linked list.
*/
return 0;
}
int main(void){
//
void print_node(struct Node*);
void insert_node(struct Node**, struct Node**, int, char, char*, char);
srand(time(NULL));
char** board;
char state[] = "GAME START";
char flag[] = "GAME OVER!";
char character;
int integer;
/* declare a linked list below*/ //COMPLETED
//struct Node* head = NULL;
//struct Node* second = NULL;
//head = (struct Node*)malloc(sizeof(struct Node));
//second = (struct Node*)malloc(sizeof(struct Node));
board = initialization();
do{
display_state(state, board);
if(display_state)
/*modify the accept_input function
* accept input function should return
* a temp node, which stores the current valid
* input (i.e. character and letter)
*/
accept_input(&character, &integer);
if(character == 'Z' && integer == 0)
break;
/*modify the update_state function
* update_state function should accept
* the head node of linked list and the
* temp node
*/
update_state(state, board, character, integer);
} while((character != 'Z' || integer != 0) && strcmp(state, flag) );
/*modify the teardown function
* tear_down function should accept
* a head node of linked list
*/
teardown(board);
return 0;
}
//modularize insertNode, etc. inito own functions
Try this
void print_node(struct Node *h) {
if(h != null){
printf("%c\n", h->charInput);
printf("%s\n", h->ship_type);
print_node(h->next);
}
}
I noticed you call your print function in update_state, which means you are storing to the file every move.
number 1, you need to append to the file and not write
change:
fPTR = fopen("log.txt", "w");
to:
fPTR = fopen("log.txt", "a");
And change your write function to:
//will be converted to a write to file function
void print_node(struct Node *h, FILE *fPTR){
printf("got this far");
if (h == NULL) {
printf("THE LIST IS EMPTY\n");
}
else{
printf("\nThis move was:\n");
printf("%c\n", h->charInput);
printf("%s\n", h->ship_type);
printf("%d\n", h->intInput);
printf("%s\n", h->currentState);
fprintf(fPTR, "Fired at %c%d. %s - %s. \n", h->charInput, h->intInput, h->currentState, h->ship_type);
fclose(fPTR);
}
}
This is assuming your linkedist head is created correctly
EDIT: This code gets the last move played and adds it to the file, you will have to delete the file whenever you start a new game.

C programming, only the first if statement works

I was wondering if anyone could help me understand why only my first if statements is working. Basically, I am working on a l33t speak convertor (lol) and only my first if statement works, here is my code:
#include<stdio.h>
#include<string.h>
void translate (char blurp[]);
int main(void) {
char message[1024];
printf("enter a message: \n");
fgets(message, 1024, stdin);
translate(message);
return 0;
}
void translate (char blurp[]) {
int i;
int length;
length = strlen(blurp);
printf("\nHere it is translated: \n");
for ( i = 0; i != length; i++) {
if (blurp[i] == 'a') {
blurp[i] = '4';
printf("%c", blurp[i]);
}
else if (blurp[i] == 'b') {
blurp[i] = '8';
printf("%c", blurp[i]);
}
else if (blurp[i] == 'e') {
blurp[i] = '3';
printf("%c", blurp[i]);
}
else if (blurp[i] == 'i') {
blurp[i] = '|';
printf("%c", blurp[i]);
}
else if (blurp[i] == 'o') {
blurp[i] = '0';
printf("%c", blurp[i]);
}
else if (blurp[i] == 's') {
blurp[i] = '5';
printf("%c", blurp[i]);
}
else {
printf("%c", blurp[i]);
}
}
}

Resources