PDA

View Full Version : Read from a file



matulik
26th April 2010, 17:23
Hello.
I want to read data from file to the multi-dimensional array.
For example, I have data in file:

|1 2 3 4 5|
|2 3 4 5 1|
|3 2 1 5 2|
|2 6 3 1 2|

and want to assign this to the table. In c++ i do this that:



ifstream file("name");

for(int i=0; i<4; i++)
for(int n=0; n<4; n++)
file>>Data[i][n];


but here this not work.

I try to use QFile and QTextStream but I still dont know how to do it.

TheJim01
26th April 2010, 17:50
Check for failbits. If your file format is the same as the example you gave, then there will be errors reading the data from standard input.

matulik
26th April 2010, 18:36
Ok, but I asking about another way to read from file (the same as the example), becouse ifstream call me:


(...)mainwindow.cpp:16: error: ‘ifstream’ was not declared in this scope

though I include fstream at the start of file..

squidge
26th April 2010, 18:54
Qt is not a language, it's a framework. Whilst it's preferably to use QFile, you don't have to.

TheJim01
26th April 2010, 19:02
Mole is right. You're using C++ (the language) to build an application. Qt (the framework) enhances and provides pre-built functionality for your application.

For the C++ side of this question (which is really beyond the scope of these forums), you may have included fstream, but what namespace are you using? If you didn't tell the compiler you're pulling this functionality from the standard namespace ("using namespace std;" or "using std::ifstream;"--the latter being preferred), you'll need to declare "ifstream" as "std::ifstream".

These all do the same thing:

#include <fstream>

int main()
{
std::ifstream test("test.txt");
}
#include <fstream>
using namespace std; // not preferred

int main()
{
ifstream test("test.txt");
}
#include <fstream>
using std::ifstream;

int main()
{
ifstream test("test.txt");
}Like I said, explaining this further is well beyond the scope of these forums.

From a Qt and QFile perspective, look at the docs for QFile. It's pretty easy to read a simple text file.