How to copy a character from basic string into a vector string? - 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.

Related

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());

Char Array Returning Integers

I've been working through this exercise, and my output is not what I expect.
(Check substrings) You can check whether a string is a substring of another string
by using the indexOf method in the String class. Write your own method for
this function. Write a program that prompts the user to enter two strings, and
checks whether the first string is a substring of the second.
** My code compromises with the problem's specifications in two ways: it can only display matching substrings to 3 letters, and it cannot work on string literals with less than 4 letters. I mistakenly began writing the program without using the suggested method, indexOf. My program's objective (although it shouldn't entirely deviate from the assignment's objective) is to design a program that determines whether two strings share at least three consecutive letters.
The program's primary error is that it generates numbers instead of char characters. I've run through several, unsuccessful ideas to discover what the logical error is. I first tried to idenfity whether the char characters (which, from my understanding, are underwritten in unicode) were converted to integers, considering that the outputted numbers are also three letters long. Without consulting a reference, I know this isn't true. A comparison between java and javac outputted permutation of 312, and a comparison between abab and ababbab ouputted combinations of 219. j should be > b. My next thought was that the ouputs were indexes of the arrays I used. Once again, this isn't true. A comparison between java and javac would ouput 0, if my reasoning were true.
public class Substring {
public static char [] array;
public static char [] array2;
public static void main (String[]args){
java.util.Scanner input = new java.util.Scanner (System.in);
System.out.println("Enter your two strings here, the longer one preceding the shorter one");
String container1 = input.next();
String container2 = input.next();
char [] placeholder = container1.toCharArray();
char [] placeholder2 = container2.toCharArray();
array = placeholder;
array2 = placeholder2;
for (int i = 0; i < placeholder2.length; i++){
for (int j = 0; j < placeholder.length; j ++){
if (array[j] == array2[i]) matcher(j,i);
}
}
}
public static void matcher(int higher, int lower){
if ((higher < array.length - 2) && (lower < array2.length - 2))
if (( array[higher+1] == array2[lower+1]) && (array[higher+2] == array2[lower+2]))
System.out.println(array[higher] + array[higher+1] + array[higher+2] );
}
}
The + operator promotes shorts, chars, and bytes operands to ints, so
array[higher] + array[higher+1] + array[higher+2]
has type int, not type char which means that
System.out.println(...)
binds to
System.out.println(int)
which displays its argument as a decimal number, instead of binding to
System.out.println(char)
which outputs the given character using the PrintStream's encoding.

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

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.

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