Comparing a string in a struct with a string in an array - struct

I have an array of structs, one of the elements in the struct is a string, and i need to compare those strings with other strings in an array of 12 strings. strcmp does not seem to work for me. I know i need to make seperate function to compare the the strings and return the value as a bool, but cant figure out how to make the compare function work.
The struct
typedef struct{
char *hometeam[Max_number_of_chars], *awayteam[Max_number_of_chars];
int playround, date_day, date_month, date_year,
time_hour, time_minute, home_score, away_score, crowd_thousand,
crowd_hundred;
} match;
The array of strings
char *teams[Number_of_teams] = {"AGF","AAB","SDR","RFC",
"EFB","BIF","SIF","OB",
"FCK","FCM", "ACH","FCN"};
the line where i need the compare_function
if(compare_names(all_games[i].hometeam, teams[j])==0) {//crazy stuff}
EDIT: What i need help with is making function that compares the string value from *teams[j] with the string value from all_games[i].hometeam. But i dont know how to pass the specific part of the struct all_games[i].hometeam to the compare_function, where i want it to be a char string.

// Assuming char *teams[Number_of_teams] is globally defined.
int find_match(struct match)
{
for(i=0; i < Number_of_teams; i++){
if(strcmpi(match.hometeam, teams[i]) == 0){
return i;
}
}
return -1;
}
The logical flow of what you want to do isn't clear, but you can try something like above.

Related

How to copy a character from basic string into a vector string?

//Defining the class
class Hangman
{
private:
vector<string> dictionary; //stores all the words
vector<string> secretWord; //stores the secret word
vector<string> misses; //keeps record of wrong guesses
vector<string> displayVector; //Stores "_"
string originalWord; //stores a copy of secret word to display at the
end of game.
bool gameOver = false; //Flag to check if the player lost or
still in the game.
int totalAttempts;
public:
void selectRandWord();
};
//This is the function i am having problem in.
void Hangman::selectRandWord()
{
secretWord.clear();
//word is a basic string that stores a random word. lets say "Hello World".
string word;
srand(time(NULL));
int random = (rand() % dictionary.size()) + 1;
//I store a random word from vector to word.
word = dictionary[random];
transform(word.begin(), word.end(), word.begin(), ::tolower);
originalWord = word;
for (int index = 0; index < word.length(); index++)
{
//This line has the error: [Error] invalid user-defined conversion from 'char' to 'std::vectorstd::basic_string<char >::value_type&& {aka std::basic_string&&}' [-fpermissive]
//What I am trying to do is take each character from word(for example: "H") and push it back into the vector string secretWord.
secretWord.push_back(word[index]);
}
}
Your secretWord is now a vector<string> type, so it's a collection of possibly many words, I'm not sure if that's what you really intend to have judging by the name. If it indeed is ok and you want to store every single character from word as a separate string in secretWord, then you need to replace push_back call with emplace_back call as the other method actually does two things at a time: constructs a string from the char you pass to it and appends the string to the end of the container, like this
secretWord.emplace_back(1, word[index]);
Mere push_back fails because it needs to be provided with an object of the type your vector stores, so you could also solve your problem by explicitly constructing a string from your char:
secretWord.push_back(string(1, word[index]));
I suggest you give a read to these: emplace back reference and push back reference if you're interested in copy/move details.

Grabbing first number in string after some keyword occurrence in C++ (Arduino)

I have a string coming from PC through serial to a microcontroller (Arduino), e.g.:
"HDD: 55 - CPU: 12.6 - Weather: Cloudy [...] $";
by this function I found:
String inputStringPC = "";
boolean stringCompletePC = false;
void serialEvent() {
while (Serial.available()) {
char inChar = (char)Serial.read();
inputStringPC += inChar;
if (inChar == '$') // end marker of the string
{
stringCompletePC = true;
}
}
}
I would like to extract the first number of it after the word HDD, CPU and also get the string after Weather (ie "cloudy"); my thinking is something like that:
int HDD = <function that does that>(Keyword HDD);
double CPU = <function that does that>(Keyword CPU);
char Weather[] = <function that does that>(Keyword Weather);
What is the right function to do that?
I looked into inputStringSerial.indexOf("HDD") but I am still a learner to properly understand what it does and don't know if theres a better function.
My approach yielded some syntax errors and confused me with the difference in usage between "String inputStringSerial" (class?) and "char inputStringSerial[]" (variable?). When I do 'string inputStringSerial = "";' PlatformIO complains that "string" is undefined. Any help to understand its usage here is greatly appreciated.
Thanks a bunch.
The String class provides member functions to search and copy the contents of the String. That class and all its member functions are documented in the Arduino Reference:
https://www.arduino.cc/reference/tr/language/variables/data-types/stringobject/
The other way a list of characters can be represented is a char array, confusingly also called a string or cstring. The functions to search and copy the contents of a char array are documented at
http://www.cplusplus.com/reference/cstring/
Here is a simple Sketch that copies and prints the value of the Weather field using a String object. Use this same pattern - with different head and terminator values - to copy the string values of the other fields.
Once you have the string values of HDD and CPU, you'll need to call functions to convert those string values into int and float values. See the String member functions toInt() and toFloat() at
https://www.arduino.cc/reference/en/language/variables/data-types/string/functions/toint/
or the char array functions atoi() and atof() at
http://www.cplusplus.com/reference/cstdlib/atoi/?kw=atoi
String inputStringPC = "HDD: 55 - CPU: 12.6 - Weather: Cloudy [...] $";
const char headWeather[] = "Weather: "; // the prefix of the weather value
const char dashTerminator[] = " -"; // one possible suffix of a value
const char dollarTerminator[] = " $"; // the other possible suffix of a value
void setup() {
int firstIndex; // index into inputStringPC of the first char of the value
int lastIndex; // index just past the last character of the value
Serial.begin(9600);
// find the Weather field and copy its string value.
// Use similar code to copy the values of the other fields.
// NOTE: This code contains no error checking for unexpected input values.
firstIndex = inputStringPC.indexOf(headWeather);
firstIndex += strlen(headWeather); // firstIndex is now the index of the char just past the head.
lastIndex = inputStringPC.indexOf(dollarTerminator, firstIndex);
String value = inputStringPC.substring(firstIndex, lastIndex);
Serial.print("Weather value = '");
Serial.print(value);
Serial.println("'");
}
void loop() {
// put your main code here, to run repeatedly:
}
When run on an Arduio Uno, this Sketch produces:
Weather value = 'Cloudy [...]'

Cannot insert character in string

So basically my function goes through every character in a string and inserts each character onto another string so it results in the initial string being reversed. I've looked up online but the answers to this problem seem to not work anymore, I'm not sure if it's because they are from 5+ years ago or I'm getting something wrong somewhere. My code goes like this:
long reverse_num(long n){
string new_str = "";
string my_str = to_string(n);
int my_int;
for (unsigned i = 0; i < my_str.size(); ++i){
new_str.insert(0, char my_str[i]);
}
my_int = stol(new_str);
return my_int;
}
The error given is: expected primary-expression before 'char'
new_str.insert(0, char my_str[i]);
What am I doing wrong?
Thanks!
First, you shouldn't specify the char type in the insert expression. Also, there isn't a string insert function that matches what you're doing here; you probably want one of these:
basic_string& insert(size_type pos, size_type n, charT c);
iterator insert(const_iterator p, charT c);
So your insert line should be one of these:
new_str.insert(0, 1, my_str[i]);
new_str.insert(new_str.begin(), my_str[i]);
Your type cast syntax was bad, but you appear to be attempting to insert a char into an std::string. This is the function you appeared to be going for:
http://en.cppreference.com/w/cpp/string/basic_string/insert
basic_string& insert( size_type index, size_type count, CharT ch );
Try
new_str.insert(0, 1, my_str[i]);
You also could have used http://en.cppreference.com/w/cpp/algorithm/reverse
std::reverse(my_str.begin(), my_str.end());

Arduino: String to int gets strange values

I want to convert a String to an int, and all I could find is that you have to convert the String to a char array and then cast this array to an int, but my code produces strange values and I can't figure out what the problem is.
void ledDimm(String command)
{
// Get the Value xx from string LEDDimm=xx
String substring = command.substring(8, command.length());
Serial.println("SubString:");
Serial.println(substring);
Serial.println("SubString Length:");
Serial.println(substring.length());
// Create a Char Array to Store the Substring for conversion
char valueArray[substring.length() + 1];
Serial.println("sizeof ValueArray");
Serial.println(sizeof(valueArray));
// Copy the substring into the array
substring.toCharArray(valueArray, sizeof(valueArray));
Serial.println("valueArray:");
Serial.println(valueArray);
// Convert char array to an int value
int value = int(valueArray);
Serial.println("Integer Value:");
Serial.println(value);
// Write the Value to the LEDPin
analogWrite(LEDPin, value);
}
And the serial output looks like this:
Received packet of size 11
From 192.168.1.4, port 58615
Contents:
LEDDimm=100
SubString:
100
SubString Length:
3
sizeof ValueArray
4
valueArray:
100
Integer Value:
2225
I expected to get an int with the value of 100 but the actual int is 2225?! What have I done wrong here?
There is even an (undocumented) toInt() method in the String class:
int myInt = myString.toInt();
You need to use the function int value = atoi(valueArray); where valueArray is a null terminated string.
The toInt () method is very useful in this aspect, but I found that it is able to convert only strings of length five or less, especially a value less than 65535 as its the maximum value int can take. Over this value, it just gives random numbers (overflowing values). Please be aware of this when you use this method as it killed a lot of my useful time to figure this out. Hope it helps.

Binary search for specific value in array of structs

I wrote this function that uses a binary search to look for a specific value in an array of structs. Why doesn't it compile?
I'm getting this error:
prog.c:224: error: subscripted value is neither array nor pointer
prog.c:226: error: subscripted value is neither array nor pointer
This is the function:
int FieldSearch(Field *pArr, int size, int val)
{
int low=0,high=size-1, middle;
while (low <= high)
{
middle = (low + high)/2;
if (val == pArr->Id[middle])
return middle;
else if (val < pArr->Id[middle])
high = middle -1;
else
low = middle +1;
}
return NOT_FOUND;
}
This is the field struct:
typedef struct field
{
char Id;
Coordinates location;
int area;
int price;
} Field;
Maybe the prototype is wrong...
Your problem is this statement:
pArr->Id[middle]
It looks like, but I don't have nearly enough info, that your member Id is not a pointer or an array, but merely a variable. So you cannot access it with an operator[]. You should show us what this Field object looks like.
I'm guessing you should do something like this
(pArr + middle)->Id so this will access the element of the Field array you passed into your function. Then you do have to pass in an actual array of Field structures, for this to work.
If you want to search the "array" pArr, you need to put the brackets directly behind the identitifier. This should work:
pArr[middle].Id

Resources