Reputation: 59
I am using Qt 5.2.1 and here is part of a function that I want to use in my program -
while( getline(in,str,':')
{
getline(str,'\n');
int var = atoi(str.c_str());
}
my question is how can I implement this in qt?
I searched the docs a bit and found out about readline and split but I dont know how to use them
any help is much appreciated. :D
Edit - my first getline checks for ':' in the text file and the second one picks up the number (that comes after ':') and converts it into a integer and stores it in a variable.
2 edit :
Here's how my text file looks like...
500 - 1000 : 1
1000 - 1500 : 2
1500 - 2000 : 7
2000 - 2500 : 6
the 1, 2, 7, 6 are the values that I need in my program
Upvotes: 0
Views: 7683
Reputation: 4335
I'm not totally sure what you're trying to do. If you're trying to read a file:
QFile file("/path/to/file.whatever");
if (!file.open(QIODevice::ReadOnly | QIODevice::Text) {
// error message here
return;
end
while (!file.atEnd()) {
QString line = in.readLine();
// now, line will be a string of the whole line, if you're trying to read a CSV or something, you can split the string
QStringList list = line.split(",");
// process the line here
}
QFile
closes itself when it goes out of scope.
If you're trying to split a string based on the :
delimiter you have there, use:
QStringList list = line.split(":");
EDIT:
Now that you defined what you want to do (read a like like this "value:integer"), you can easily do that with QStringList. Example:
QString input = "value:1";
QStringList tokens = input.split(":");
int second = tokens.at(1).toInt();
Of course, you'll need to use your own error checking, but this is an example of what I think you're trying to do.
Upvotes: 3