How to parse QString? - c++

I am trying to parse QString with following code:
QString name = "name.bin";
QStringList imgName = name.split(".");
qDebug() << imgName.at(0); // result is "name"
However I need just name without any ("). Then I write another code to manually delete quotes("").
Is there any easy way to split QString?

There are no " " in the string. It just contains Name
qDebug() << (imgName.at(0))[0]; // result is n

Related

How to organize or extract info from a QByteArray

I have a programm that recieves a full block in a single QByteArray. This block is "divided" with 'carriage returns' followed by 'end lines' (\r\n). In the middle of all this junk I have a date. Most specifically in the third line (between the second and the third \r\n).
Every time I try to extract this date from the ByteArray I end up with some random junk. How to be more precise with the QByteArray?
What is the best way of extracting this date without altering my ByteArray? Take in consideration that I don't know the date and it can even be in the wrong format.
Just for understanding purposes, here is an example of my ByteArray:
RandomName=name\r\nRandomID=ID\r\nRandomDate=date\r\nRandomTime=time\r\nRandomWhatever=whatever(...)
EDIT:
Sorry for bad english.
Let's say I have the following text sent to me:
ProgName = Marcus
ProgID = 180
ProgDate = 15.01.16
ProgTime = 13:39
(More info)......
However, none of this information is useful to me... except the Date. Everything was stored in a single QByteArray (Let's call it 'ba'). So this is my ba:
ProgName(space)=(space)Marcus\r\nProgID(space)=(space)180\r\nProgDate(space)=(space)15.01.16\r\nProgTime(space)=(space)13:39\r\n (keeps going)
My problem is: Storing "15.01.16" (the "ProgDate") in a QString without altering or destroying ba.
There are a variety of ways, but try one of the following solutions.
1) using split()
foreach (auto subByte, yourByteArray.replace("\r\n", "\n").split('\n')) {
qDebug() << subByte;
foreach (auto val, subByte.split('=')) {
qDebug() << val;
}
}
2) using QRegularExpression/QRegularExpressionMatchIterator, making all pair(key, value)
QRegularExpression re("(\\w+)=(\\w+)");
QRegularExpressionMatchIterator i = re.globalMatch(yourByteArray);
while (i.hasNext()) {
QRegularExpressionMatch match = i.next();
qDebug() << match.captured(0)<< match.captured(1) << match.captured(2);
}
3) using QRegularExpression/QRegularExpressionMatch
QRegularExpression re("(RandomDate)=(\\w+)");
QRegularExpressionMatch match = re.match(yourByteArray);
if (match.hasMatch())
qDebug() << match.captured(0)<< match.captured(1) << match.captured(2);

Qt, QFile write on specific line

I've run into another problem in Qt, I can't seem to figure out how to write on a specific line on a text file with QFile. Instead, everything is erased written at the beginning.
So with the given information, how would I write to a specific line in QFile?
Here are two functions.
The first function searches a file, and then gets two variables. One that finds the next empty line, one that gets the current ID number.
Second function is supposed to write. But I've looked for documentation on what I need, I've googled it and tried many searches to no avail.
Function 1
QString fileName = "C:\\Users\\Gabe\\SeniorProj\\Students.txt";
QFile mFile(fileName);
QTextStream stream(&mFile);
QString line;
int x = 1; //this counts how many lines there are inside the text file
QString currentID;
if(!mFile.open(QFile::ReadOnly | QFile::Text)){
qDebug() << "Could not open file for reading";
return;
}
do {
line = stream.readLine();
QStringList parts = line.split(";", QString::KeepEmptyParts);
if (parts.length() == 3) {
QString id = parts[0];
QString firstName = parts[1];
QString lastName = parts[2];
x++; //this counts how many lines there are inside the text file
currentID = parts[0];//current ID number
}
}while (!line.isNull());
mFile.flush();
mFile.close();
Write(x, currentID); //calls function to operate on file
}
The function above reads the file, which looks like this.
1001;James;Bark
1002;Jeremy;Parker
1003;Seinfeld;Parker
1004;Sigfried;FonStein
1005;Rabbun;Hassan
1006;Jenniffer;Jones
1007;Agent;Smith
1008;Mister;Anderson
And the function gets two bits of information that I figured I might need. I'm not too familiar with QFile and searching, but I thought that I'd need these variables:
int x; //This becomes 9 at the end of the search.
QString currentID; //This becomes 1008 at the end of the search.
So I passed in those variables to the next function, at the end of function 1. Write(x, currentID);
Function 2
void StudentAddClass::Write(int currentLine, QString idNum){
QString fileName = "C:\\Users\\Gabe\\SeniorProj\\Students.txt";
QFile mFile(fileName);
QTextStream stream(&mFile);
QString line;
if(!mFile.open(QFile::WriteOnly | QFile::Text)){
qDebug() << "Could not open file for writing";
return;
}
QTextStream out(&mFile);
out << "HelloWorld";
}
I've left out any attempts at fixing the problem myself, all this function does is replace all the contents of the text file with "HelloWorld".
Does anyone know how to write on a specific line, or at least go to the end of the file and then write?
If the line you want to insert into the file is always the last line (as the function 1 suggest) you can try to open the file in append mode using QIODevice::Append in your Write method.
If you want to insert a line in the middle of the file, I suppose an easy way is to use a temp file (or, if it is possible, to load the lines into a QList, insert the line and write the list back to the file)
QString fileName = "student.txt";
QFile mFile(fileName);
if(!mFile.open(QFile::Append | QFile::Text)){
qDebug() << "Could not open file for writing";
return 0;
}
QTextStream out(&mFile);
out << "The magic number is: " << 4 << "\n";
mFile.close();
The above code snippet will append the text "The magic number is: 4" , at the end of the file.

QString splitting multiple delimiters

I'm having trouble splitting a QString properly. Unless I'm mistaken, for multiple delimiters I need a regex, and I can't seem to figure out an expression as I'm quite new to them.
the string is text input from a file:
f 523/845/1 524/846/2 562/847/3 564/848/4
I need each number seperately to put into an array.
Some codes....
QStringList x;
QString line = in.readLine();
while (!line.isNull()) {
QRegExp sep("\\s*/*");
x = line.split(sep);
Any pointers?
Cheers
Change your regular expression like this:
QRegExp sep("(\\s+|/)");
then x will have every number.
I found it quite useful to try out RegEx's interactively. Nowadays there are a lot of online tools even, for example: http://gskinner.com/RegExr/
You can put your search text there and play with the RegEx to see what is matched when.
You could use the strtok function, which split a QString with one or more different tokens.
It would be like this:
QString a = "f 523/845/1 524/846/2 562/847/3 564/848/4";
QByteArray ba = a.toLocal8Bit();
char *myString = ba.data();
char *p = strtok(myString, " /");
while (p) {
qDebug() << "p : " << p;
p = strtok(NULL, " /");
}
You can set as many tokens as you need. For further info visit the cplusplus page of this particular function. http://www.cplusplus.com/reference/cstring/strtok/
Regards!.

How do I insert a variable result into a string in C++

I just started learning C++ in Qt and I was wondering how can I put a variables result in a string? I'm trying to use this for a simple application where someone puts their name in a text field then presses a button and it displays there name in a sentence. I know in objective-c it would be like,
NSString *name = [NSString stringWithFormatting:#"Hello, %#", [nameField stringValue]];
[nameField setStringValue:name];
How would I go about doing something like this with C++? Thanks for the help
I assume we're talking about Qt's QString class here. In this case, you can use the arg method:
int i; // current file's number
long total; // number of files to process
QString fileName; // current file's name
QString status = QString("Processing file %1 of %2: %3")
.arg(i).arg(total).arg(fileName);
See the QString documentation for more details about the many overloads of the arg method.
You donĀ“t mention what type your string is. If you are using the standard library then it would be something along the lines of
std::string name = "Hello, " + nameField;
That works for concatenating strings, if you want to insert other complex types you can use a stringstream like this:
std::ostringstream stream;
stream << "Hello, " << nameField;
stream << ", here is an int " << 7;
std::string text = stream.str();
Qt probably has its own string types, which should work in a similar fashion.
I would use a stringstream but I'm not 100% sure how that fits into your NSString case...
stringstream ss (stringstream::in);
ss << "hello my name is " << nameField;
I think QString has some nifty helpers that might do the same thing...
QString hello("hello ");
QString message = hello % nameField;
You could use QString::sprintf. I haven't found a good example of it's use yet, though. (If someone else finds one, feel free to edit it in to this answer).
You might be interested in seeing information about the difference between QString::sprintf and QString::arg.

How to call qDebug without the appended spaces and newline?

I'm using the the C++/Qt print function qDebug,
but sometimes I would like to control how ", space and newline is appended
and not use the default qDebug.
Let's take a simple example:
QString var1("some string");
int var2 = 1;
qDebug() << var1 << "=" << var2;
This will print
"some string" = 1
But Let's say that I don't like the appended " and space
and would like the print to look like
some string=1
How to I then call qDebug?
Note: There is a function in qDebug called nospace, but it will remove the spaces.
But the " is still there.
If I use this:
qDebug().nospace() << var1 << "=" << var2;
I get:
"some string"=1
But please note that I have still not found a way to get rid of the ending newline.
/Thanks
It would be best to understand how QDebug works internally. That way you can easily modify it to suit your needs. Whenever you use the qDebug() function, it returns a QDebug object. By default QDebug always outputs a space after any use of operator <<.
The QDebug class internally contains a QString. Every time you use operator << you are appending to that internal QString. This QString is printed via qt_message_output(QtMsgType, char*) when the QDebug object is destroyed.
By default qt_message_output always prints the string followed by a newline.
Normal Output
qDebug() << "Var" << 1;
This will output Var 1. This is because qDebug will create a QDebug object which appends a space after each call to operator <<. So that will be Var + + 1 + .
Without Spaces
You can use QDebug::nospace to tell QDebug not to append a space after each call to operator <<.
qDebug().nospace() << "Var" << 1;
This will output Var1 as that QDebug object is no longer printing spaces.
Without New Lines
Not adding the \n at the end of the string is a little bit harder. Since QDebug internally only passes the string to qt_message_output when it is destroyed, you can delay the destruction of that QDebug object -
QDebug deb = qDebug();
deb << "One" << "Two";
deb << "Three";
This will print One Two Three and then append a new line.
If you never want a new line to be printed, you will have to change the behaviour of qt_message_output. This can be done by installing a custom handler.
void customHandler(QtMsgType type, const char* msg) {
fprintf(stderr, msg);
fflush(stderr);
}
// Somewhere in your program
qInstallMsgHandler(customHandler);
qDebug() << "One" << "Two";
qDebug().noSpace() << "Three" << "Four";
This will print One Two ThreeFour.
Be warned that this will affect all of the qDebug statements in your program. If you want to remove the custom handler, you should call qInstallMsgHandler(0).
qDebug(const char* msg, ...)
As indicated by the other answers you can also use the qDebug function to print strings in a format similar to that of printf. This way you can avoid the extra spaces that are appended by QDebug.
However, qDebug internally still uses qt_message_output, so you will still get a newline at the end unless you install your own handler.
Try this format: qDebug("%s=%d", "string", 1);
In this case qDebug uses printf formatting
P.S. Adapted for your example: qDebug("%s=%d", var1.toStdString().c_str(), var2);
Since Qt 5.4 you can also write:
qDebug().nospace().noquote() << var1;
Combining some of the above answers you can use
qDebug() << qPrintable(var1);
to eliminate the surrounding quotes.
I also experienced the quotes problem. The solution is to not pipe QString() into the stream but instead QString(...).toStdString().c_str().
I've built myself a small convenience macro to easily get around this:
#define Q(string) (string).toStdString().c_str()
Now everytime you use a QString, do it like that:
qDebug() << Q(var1) << "=" << var2;
The file $(QTDIR)/src/corelib/io/qdebug.h contains almost all definitions for the debug output methods. One of them is:
inline QDebug &operator<<(const QString & t) { stream->ts << '\"' << t << '\"'; return maybeSpace(); }
So there is no "official" way to suppress the quotes, but you can of course change qdebug.h or use your own copy or a modified and renamed copy of the QDebug class.
Another way is to use your own message handler.
Hope this helps.
Instantiate a QDebug object and output to it:
QDebug dbg = qDebug().nospace().noquote();
dbg << var1 << "=" << var2;
Yields:
some string=1
Output to the dbg object all you want -- there won't be a newline until it goes out of scope. For example:
char var1[] = "some string";
int var2 = 1;
{
QDebug dbg = qDebug().nospace().noquote();
dbg << var1 << "=" << var2;
// keep using "dbg"; there's no newline ('\n') until it destructs
dbg << "...";
for (int i = 5; i <=9; ++i)
dbg << i;
}
Outputs:
some string=1...56789