0

I have a text file, with many lines that goes like this:

1,1
2
7,7
11,11

13,13

0,0

I would like to take every integer and assign it to a variable, using the text file system that Qt provides. I've thought about reading every line, then using QString::split(), but I think that there are easier methods to do this.

taocp
  • 23,276
  • 10
  • 49
  • 62
Kanghu
  • 561
  • 1
  • 10
  • 23
  • 5
    `std::ifstream` is a good starting point. –  May 24 '13 at 22:35
  • What exactly do you want the results to look like? Do you just want to get an array of ints? An array of rows, each of which is an arrays of ints? Or… what? – abarnert May 24 '13 at 22:38
  • Also, do you really have lines with different numbers of values, or is that `2` all by itself a mistake? If your data is a CSV, there are plenty of [CSV solutions for Qt]((http://qt-project.org/search/tag/csv))) already built, but that may not help you here. – abarnert May 24 '13 at 22:39
  • I outlined one possibility in [my answer](http://stackoverflow.com/a/1895584/179910) to a previous question. – Jerry Coffin May 24 '13 at 22:47
  • I need to take the numbers from one line, draw something at that position, then get to the next line. I don't really need to save the numbers, after drawing I can just go on. – Kanghu May 24 '13 at 23:24

1 Answers1

1

Use QFile::readAll, pass it to QString in constructor, split it to QStringList, iterate through it with toInt function.

Edited to suit better your purpose, this is simple console test app (i would assume, that line with only number 2 is a mistake and every line should have at least two numbers).

main.cpp:

QFile f("file.txt");
f.open(QIODevice::ReadOnly);
foreach (QString i,QString(f.readAll()).split(QRegExp("[\r\n]"),QString::SkipEmptyParts)){
    QPoint pos;
    pos.setX(i.section(",",0,0).toInt());
    pos.setY(i.section(",",1,1).toInt());
    // draw something here, pos holds your coords in x as first valur and in y second (pos.x(), pos.y() )
    qDebug()<<pos;
}
f.close();

your coords will hold QPoint pos, it will have one line of coords at a time, so you can draw points or do whatever you want with them. file.txt should be in a dir with a binary file or you can change as it suit you.

Shf
  • 3,463
  • 2
  • 26
  • 42