tarabyte
tarabyte

Reputation: 19172

How to pop off first string of a QString?

For example, my QString is "12 1,2 3,4" and I want to pop off "12" and then maybe trim off the leading whitespace so that it becomes " 1,2 3,4"

This is part of reading from an input file.

QFile input_file("path/to/testfile.txt");

if (!input_file.exists()) {
  dbg << "File does NOT exist" << endl;
  exit(1);
}

if (!input_file.open(QFile::ReadOnly)) {
  exit(2);
}

QDataStream input_stream(&input_file);
while (!input_file.atEnd()) {
  QString line = input_stream.readLine();
  // how do I parse off that first number?

Upvotes: 1

Views: 929

Answers (2)

Nejat
Nejat

Reputation: 32635

You can split the string into substrings seperated by any character :

QStringList tokens= line.split(" ",QString::SkipEmptyParts);

Now the first number can be accessed by tokens[0].

Removing the first element and trimming the string is simply like :

line.remove(0,tokens[0].length()).trimmed();

Upvotes: 1

Drew Dormann
Drew Dormann

Reputation: 63735

It looks like QTextStream would do the job, where your comment currently is.

QTextStream seems to be the QT equivalent of std::istringstream, designed to parse text that's separated by whitespace.

QTextStream text_stream( &line );
QString that_first_numer;

text_stream >> that_first_number;  // Read text up to whitespace
line = text_stream.read_line();    // Copy the remaining text back to line.

Upvotes: 1

Related Questions