Parsing RapidJSON string returns NULL on brackets - c++

{"1":"value","data":[A,B,C]}
1 returns value.
data returns null.
Adding quotations "[A,B,C]" isn't an array anymore.
rapidjson::Value &arr = document["data"];
if( !arr.IsArray() || arr.Size() != 3 )
{
Return;
}
else
{
x = arr[rapidjson::SizeType(0)].GetDouble();
y = arr[rapidjson::SizeType(1)].GetDouble();
z = arr[rapidjson::SizeType(2)].GetDouble();
};
How should I properly handle the [bracketed array]?
I have quite a lot of objects without quotes. Can I handle the objects without quotes?

Related

How to check if String contains only operators and numbers in as3?

How to check if String contains only operators and numbers.
The string which may contains 0-9 and +,-,.,/,*,X,=
For example : 28+30-22*5 = when i check this it should return true. If this contains a character then it will return false.
Can we use regexp for this.
This is totally primitive and straightforward, but it should do the trick:
// A collection of valid characters.
const VALID:String = "0123456789+-*/=X ";
function check(sample:String):Boolean
{
for (var i:int = 0; i < sample.length; i++)
{
// Let's iterate the given String, char by char.
var aChar:String = sample.charAt(i);
// The .indexOf(...) method returns -1 if there's no match.
if (sample.indexOf(aChar) < 0)
{
return false;
}
}
// If we got as far as here, it means
// there's no invalid characters in the sample.
return true;
}
trace(check("28+30-22*5 =")); // true
trace(check("a = 100 * 3 / 10")); // false
Of course you can do it the RegExp way, but it will probably be the same logic, just less readable, more difficult to handle, and not measurably faster.

Setting an array as a modifiiable parameter of a function in C++

I'm trying to set an array as an input parameter to a self-made function, in which I want to modify the values of the array. For that, I tried to set the input array in the definition of the function as a pointer, but gave me some trouble.
The part of the *.hpp file can be seen here:
void CrossWall(int, int, bool[]);
The part of the *.cpp file is the next one:
void NODE::CrossWall(int robot_x, int robot_y, bool done_checking[]){
if (((robot_x+1) > (current_map.CheckLength() - 1)) && !done_checking[3] ){
available_movements[3] = 0;
done_checking[3] = true;
}
if (((robot_x-1) < 0 ) && !done_checking[2]){
available_movements[2] = 0;
done_checking[2] = true;
}
if (((robot_y+1) > (current_map.CheckHeight() - 1)) && !done_checking[0]){
available_movements[0] = 0;
done_checking[0] = true;
}
if (((robot_y-1) < 0 ) && !done_checking[1]){
available_movements[1] = 0;
done_checking[1] = true;
}
}
The array I want to modify is the array of bools (the only one there).
I think I found a point of confusion:
won't do it because it isn't a pointer.
In fact, it IS a pointer: What is array to pointer decay?

c++: Run a function 8 times and add each answer to an array or JSON it

I'm super new to C++ and am trying to build a json file that contains x0...x7 of the files that gets parsed from a pre-defined function so that it can compose a JSON string to give to R. so that it can open a socket to R and send this piece of JSON to it.
however, im kinda stuck here, here is what i have:
std::map<std::string,std::string>::const_iterator qIter;
std::string variable;
std::map<string,string> mymap;
variable = "x";
for (int i=1,i<=7,i++){
float variable+i = ( (qIter = request.getQuery().find(variable+i))
== request.getQuery().end()
)
? 0.0
: atof(qIter->second.c_str());
if ( !isLegalNumber(request.getQuery(),variable+i,variable+i) )
{
strcpy(filePath,"yourErrorFilename.html");
}
else
{
// I want to add the x0 or xn variable here into a json
// The value is now in variable 'x'of something
}
}
Any insights appreciated.
edit: here's my isLegalNumber() method
bool isLegalNumber (const std::map<std::string,std::string>&
map,
const std::string& varName,
float& value
)
{
float temp;
char* cPtr;
std::map<std::string,std::string>::const_iterator
iter = map.find(varName);
if (iter == map.end())
return(false);
temp = strtod(iter->second.c_str(),&cPtr);
if ( (*cPtr != '\0') || (cPtr == iter->second.c_str()) )
return(false);
value = temp;
return(true);
}
im trying to convert a string/ dictionary into a json,
the first question would be how to add it into a dictionary,
and second, how to convert that dictionary into JSON.
basically i want the json to look like
{
x1: value of x1,
x2: value of x2,
....
x7: value of x7
}
I'm not totally clear what you're trying to do in your example code. Specifically, I don't know what the string value variable is used for. I'm guessing you actually want to define an array of floats. You can also skip the first step where you're setting the value to either 0.0 or atof(...) since your isLegalNumber function sets it later anyway. e.g.
float x[8] = {0.0f};
// Note that arrays in C++ are zero-indexed, so your iteration variable should start at 0
for (int i=0; i<=7; i++) {
std::string varName = "x";
varName.push_back(std::to_string(i+1)); // Append the index
if ( !isLegalNumber(request.getQuery(), varName, x[i] ) {
// Error
} else {
// Add to JSON structure
}
}
Once you've got that sorted out, for working with JSON in C++, I would strongly recommend using an existing open-source library such as JSON for Modern C++, rather than rolling your own implementation. This will make it much easier to build the JSON structure you need and ensure that it is properly formatted.
That library has quite thorough documentation, and it allows you to define JSON structures using very similar syntax to the actual JSON you're trying to write, e.g.
json j2 = {
{"pi", 3.141},
{"happy", true},
{"name", "Niels"},
// ...
};
Or in your specific case, define json j; outside the loop, and then in your if case you can do:
j[varName] = x[i];
And then you can convert it to a string using std::string s = j.dump();.

non-standard syntax use '&' to create a pointer to member c++

I have created two vectors o3 ( a vector to hold the words from a string) and o4 ( a vector to hold those vector of words). In the if statement, once ";" has been found in the vectoro3[i], I want to stop putting words from thato3[i]` into o4, and go to the next line held in o3. I am getting the error "non-standard syntax use '&' to create a pointer to member c++" in the line commented as ERROR. Any help is highly appreciated. Thanks!
while (getline(myfile, line, (char)32)) // first read entire line into a
//string
// problem : this also reads empty lines
// and gives error
// while returning words
{
abc2.push_back(line); // inserting individual strings into a vector
//cout << abc[i] << "\n"; // use this to see
// them as a vector of lines
//i++;
}
for (int i = 0; i < abc.size(); i++)
{
single_line = abc[i];
if (((single_line[0] >= 'A') && (single_line[0] <= 'Z')) ||
((single_line[0] >= 'a') && (single_line[0] <= 'z')))
{
if (abc[i] != "")
{
o3 = output_words(abc[i], (char)32); // function to separate
//words in a line
int j1 = 0; int j2 = 0;
while (j2 < o3.size())
{
if (o3[j2] != "" && "\t") // *IMP* require this line to
// get words
// irrespective of spaces
{
if (o3[j2].find != ";") // ERROR
{
o4.resize(i + 1);// NO CLUE WHY IT WORKED WITH
// i+1 resize???!!!
o4[i].push_back(o3[j2]);
j2++;
}
else
{
j2++;
}
}
else
{
j2++;
}
}
}
}
else
{
o3 = { "" }; // o1 will be null vector (i.e will contain
// nothing inside)
o4.push_back(o3);
}
}
The result of expression o3[j2].find is a member of o3[j2] by the name find. That result is then compared with the string literal in the full expression o3[j2].find != ";".
The warning message seems to imply, that decltype(o3[j2])::find is a member function. In this context, the name of the member function decays to a member function pointer. The compiler warns you because such implicit conversion is ill-formed according to the standard, but supported as a language extension by the compiler. The standard way is to use the address-of operator & explicitly.
Comparing (a pointer to) a member function to a string literal makes little sense. You may have intended to call the member function instead. To call a function, you add the argument list surrounded by parenthesis: o3[j2].find(/* arguments */).
Assuming decltype(o3[j2]) is std::string (you forgot to declare o3), then the comparison with string literal also seems suspicious. std::string::find returns the index of the found substring or character. Comparing an integer to a string literal doesn't make any sense either. I recommend pondering what that line is supposed to do.

hashkey collision when removing C++

To make the search foreach "symbol" i want to remove from my hashTable, i have chosen to generate the hashkey i inserted it at. However, the problem that Im seeing in my remove function is when I need to remove a symbol from where a collision was found it previously results in my while loop condition testing false where i do not want.
bool hashmap::get(char const * const symbol, stock& s) const
{
int hash = this->hashStr( symbol );
while ( hashTable[hash].m_symbol != NULL )
{ // try to find a match for the stock associated with the symbol.
if ( strcmp( hashTable[hash].m_symbol , symbol ) == 0 )
{
s = &hashTable[hash];
return true;
}
++hash %= maxSize;
}
return false;
}
bool hashmap::put(const stock& s, int& usedIndex, int& hashIndex, int& symbolHash)
{
hashIndex = this->hashStr( s.m_symbol ); // Get remainder, Insert at that index.
symbolHash = (int&)s.m_symbol;
usedIndex = hashIndex;
while ( hashTable[hashIndex].m_symbol != NULL ) // collision found
{
++usedIndex %= maxSize; // if necessary wrap index around
if ( hashTable[usedIndex].m_symbol == NULL )
{
hashTable[usedIndex] = s;
return true;
}
else if ( strcmp( hashTable[usedIndex].m_symbol , s.m_symbol ) == 0 )
{
return false; // prevent duplicate entry
}
}
hashTable[hashIndex] = s; // insert if no collision
return true;
}
// What if I need to remove an index i generate?
bool hashmap::remove(char const * const symbol)
{
int hashVal = this->hashStr( symbol );
while ( hashTable[hashVal].m_symbol != NULL )
{
if ( strcmp( hashTable[hashVal].m_symbol, symbol ) == 0 )
{
stock temp = hashTable[hashVal]; // we cansave it
hashTable[hashVal].m_symbol = NULL;
return true;
}
++hashVal %= maxSize; // wrap around if needed
} // go to the next cell meaning their was a previous collision
return false;
}
int hashmap::hashStr(char const * const str)
{
size_t length = strlen( str );
int hash = 0;
for ( unsigned i = 0; i < length; i++ )
{
hash = 31 * hash + str[i];
}
return hash % maxSize;
}
What would I need to do to remove a "symbol" from my hashTable from a previous collision?
I am hoping it is not java's equation directly above.
It looks like you are implementing a hash table with open addressing, is that right? Deleting is a little tricky in that scheme. See http://www.maths.lse.ac.uk/Courses/MA407/del-hash.pdf:
"Deletion of keys is problematic with open addressing: If there are two colliding keys x and y with h(x) = h(y), and key x is inserted before key y, and one wants to delete key x, this cannot simply be done by marking T[h(x)] as FREE, since then y would no longer be found. One possibility would be to mark T[h(x)] as DELETED (another special entry), which is skipped when searching for a key. A table place marked as DELETED may also be re-used for storing another key z that one wants to insert if one is sure that this key z is not already in the table (i.e., by reaching the end of the probe sequence for key z and not finding it). Such re-use complicates the insertion method. Moreover, places with DELETED keys fill the table."
What you need to do is create a dummy sentinel value that represents a "deleted" item. When you insert a new value into the table, you need to check to see if an element is NULL or "deleted". If a slot contains this sentinel "deleted" value or the slot is NULL, then the slot is a valid slot for insertion.
That said, if you are writing this code for production, you should consider using the boost::unordered_map, instead of rolling your own hash map implementation. If this is for schoolwork,... well, good luck.