weird behaviour of strstr in qt program - c++

I'm a beginner, made a function which takes input from lineedit converts it into a array and then searches it to find a word. If the word is found it prints successs in a label, otherwise prints error.Problem is that it every time prints error no matter what i enter.
What am I doing wrong.
void MainWindow::on_consoleEdit_returnPressed()
{
QString text = ui->consoleEdit->text();
char enteredCmd[4096];
strcpy(enteredCmd, "Some string data");
text = enteredCmd;
//enteredCmd contains all the data that text string contains
char *open = strstr(enteredCmd, "open");
if(open != NULL) {
ui->answerLabel->setText("SUCCESS");
}
else {
ui->answerLabel->setText("ERROR");
}
}

You are testing same string every time, see this:
char enteredCmd[4096];
strcpy(enteredCmd, "Some string data");
text = enteredCmd;
this overrides text value with copy of this "Some string data" string.
Anyway you made this to complicated. QString have lots of functionality useful for you.
void MainWindow::on_consoleEdit_returnPressed()
{
QString text = ui->consoleEdit->text();
if(text.contains("open")) {
ui->answerLabel->setText("SUCCESS");
} else {
ui->answerLabel->setText("ERROR");
}
}

Your code is not searching on the text from the line edit. Your code is actually searching for "open" on the string enteredCmd, which always contains "Some string data". Thus, you should always get "ERROR" printed to your answer label.
Here's what I think you are trying to do, using QString instead of strstr:
void MainWindow::on_consoleEdit_returnPressed()
{
QString text = ui->consoleEdit->text();
if(text.contains(QStringLiteral("open"))) {
ui->answerLabel->setText("SUCCESS");
}
else {
ui->answerLabel->setText("ERROR");
}
}

QString is designed to work with many languages so it requires some conversion to get text to a C style eight bit string. You might try something like this:
char *myChar = text.toLatin1().data();

Related

How to preserve zeros at end of doubles in QJsonDocument?

I'm reading, parsing and writing back a JSON file in a QT project. Part of the requirements is that all entry's should be the same written out as declared in the source file.
One of the entries looks somewhat like this:
"SomeVal": 1.23141241242140
When I read the JSON object, the last zero (0) is removed. That does make sense, since it is not needed for normal use cases. But, since I need to preserve the whole correct number, including that last zero, this is incorrect for me. Any clue on how I can bypass this problem?
The code that reads the JSON file:
QString rawJson = "";
QFile jsonFile(filePath);
if(jsonFile.exists())
{
jsonFile.open(QFile::ReadOnly|QFile::Text);
rawJson = jsonFile.readAll();
jsonFile.close();
}
else
{
return false;
}
QJsonParseError json_parse_error;
QJsonDocument json_doc = QJsonDocument::fromJson(rawJson.toUtf8(), &json_parse_error);
if(json_parse_error.error != QJsonParseError::NoError)
{
emit SignalMessageCritical(QString(json_parse_error.errorString()));
return false;
}
this->jsonTestFile = json_doc.object();

C Builder (C++) AnsiString Length method

I am used to program in c#, but now i had to help my roommate with a c++ project.
This is the "not working code" :
void HighlightKeyWords::Highlight(TRichEdit eMemo,TRichEdit RichEdit1)
{
ifstream file("KeyWords.txt");
AnsiString temp;
int maxWordLength=0;
if(file.is_open())
{
while(file>>temp)
{ if(temp.Length()> maxWordLength)
{
maxWordLength=temp.Trim().Length();
}
keyWords.push_back(temp);
}
file.close();
}
else
{
ShowMessage("Unable to open file. ");
}
for(unsigned i=0;i<KeyWords.size();i++)
{
richEdit1->Text=KeyWords[i];
}
eMemo->Text=MaxWordLength;
}
I get a list of keywords from the file. In MaxWordLength i want to know to maximum length of a word ( words are separated by new line in the text file ). When I do the temp.Length, i get 695 ( the number of all characters in the file ). Why am I not getting the actual length of the word i am adding to the vector?
Thank you!
LE: I also did the MaxWordLength logic in the for below, the for where i put the items in the RichEdit.
Use file.getline() instead of the >> operator, which won't produce the desired output in your case, but gives you the full file content as result. So AnsiString().Length() is not your problem. Just modify part of your code to get it working as intended:
char buffer[255];
if(file.is_open()){
while(file.getline(buffer, sizeof(buffer))){
temp = AnsiString(buffer).Trim();
if(temp.Length()> maxWordLength) maxWordLength=temp.Length();
keyWords.push_back(temp);
}
file.close();
}

C++ Converting to String eventually stops working

The below method is called every second 4 times, for a while it works fine, I get the following output:
++++++++++++++++
^
^
++++++++++++++++
However after a few hundred calls, the line
String str = String(tosend);
Seems to stop working somehow and I get the output
++++++++++++++++
^
++++++++++++++++
So for whatever reason 'str' has no value. As I'm typing this it seems if I leave the application running long enough it starts working again and I get the correct output. What on earth is wrong here? I'm baffled.
void Transmit(char tosend)
{
String str = String(tosend);
const char *tosend_ready = str.c_str();
Serial.println("++++++++++++++++");
Serial.println(str);
Serial.println(tosend);
Serial.println("++++++++++++++++");
vw_send((uint8_t *)tosend_ready, strlen(tosend_ready));
vw_wait_tx();
delay(100);
}
I've no idea what String is, but this implementation can get you rid of it (looks like embedded anyway, so you shouldn't care about C-isms... right?)
void Transmit(char tosend)
{
const char buf[2] = { tosend, '\0' };
Serial.println("++++++++++++++++");
Serial.println(buf);
Serial.println(tosend);
Serial.println("++++++++++++++++");
vw_send(buf, 2);
vw_wait_tx();
delay(100);
}

Reading a random line from a txt file, then trim it in QT SDK

I'd like to ask your help with my little school project.
The task is to determine a person's gender (using 2 radio buttons) and then pick a random Japanese family name and male/female middlename. And there's the rest of the task, but it's nothing compared to this part :(
Thing is, i have managed to make the 3 .txt files (familynames.txt, malemiddlenames.txt and femalemiddlenames.txt) look like the following:
1,Akiro
2,Sakura
3,etc...
What i'd like to do is create a random number, and read the lines until it arrives to the line with the same number as my random number, then cut the number and the comma off, and display the name on the corresponding label. So far this is what i've got:
void MainWindow::famname()
{
QString familyname;
int famrand =qrand() % 76;
ui->label_2->setText(QString::number(famrand));
int i = 1;
QFile famfile("C:\Users\Ryseth\gyakorlas\_familynames.txt");
QTextStream in(&famfile);
if(famfile.open(QIODevice::ReadOnly)){
while (!in.atEnd()) {
QString line = in.readLine();
i++;
if(i==famrand){
QStringList line2 =line.split(',');
familyname = line2.at(0);
ui->label_2->setText(QString::number(famrand)+" "+QString::number(i));
ui->FamilyLabel->setText(familyname);
}//IF
}//WHILE
}//IF
famfile.close();
}//NGEN
If any of you could think of some sort of solution or if you have ANY suggestions, please don't hasitate to share it with me :D
Thank you, and have a nice day/night : Ruben
I think with Boost::Spirit::Qi you could parse your file into a std::vector< std::string > and do your operation with simple c++ methods.
But to help you with your Qt-Solution:
You never check if int famrand =qrand() % 76; produces a legal number, are there enough entries in your text file ...
int i = 1; This integer is unnecessary, the number is within the text file ...
My solution (untested):
while (!in.atEnd()) {
QString line = in.readLine();
QStringList list = line.split(",", QString::SkipEmptyParts);
bool ok;
int idx = list.at(0).toInt(&ok);
if (ok && idx == famrand) {
familyname = list.at(1).trimmed();
// ... do with your ui whatever you want
}//IF
}//WHILE
Keep in mind you have to do error handling if the conversion of string to int fails and/or the accessors of list throw (list.at(xx))
The positive thing is, you dont need an ordered text file!
I don't really understand what you are managing to do but at this line I guess you are getting the number, not the familyname.
familyname = line2.at(0); // number
familyname = line2.at(1); // family name

Arduino opening SD filename as string

I am trying to open up a file that I calculate the name into a string. However, it is just giving me compile errors as shown.
for(int i=1;;i++)
{
String temp = "data";
temp.concat(i);
temp.concat(".csv");
if(!SD.exists(temp))//no matching function for call to sdclass::exists(String&)
{
datur = SD.open(temp,FILE_WRITE);
}
}
I am a java person, so I don't see why this isn't working. I tried a few string object methods but none seem to have worked. I am a bit new at arduino programming but I understand java much better. The point of this for loop is to make a new file each time the arduino reboots.
SD.open expects a character array instead of a String, you need to convert it using the toCharArray method first. Try
char filename[temp.length()+1];
temp.toCharArray(filename, sizeof(filename));
if(!SD.exists(filename)) {
...
}
Completed Code:
for(int i=1;;i++)
{
String temp = "data";
temp.concat(i);
temp.concat(".csv");
char filename[temp.length()+1];
temp.toCharArray(filename, sizeof(filename));
if(!SD.exists(filename))
{
datur = SD.open(filename,FILE_WRITE);
break;
}
}
You will find a number of functions take char arrays instead of strings.