View Full Version : Yet another c++ question - reading multiple files
I have the following problem: My program is supposed to read data from files to an array. The files are numbered: file1.dat, file2.dat and so on. There are 24 of those files, and I really don't want to do the same step 24 times. Is there a way to write a loop along the lines of
for (int i=1; i<25, i++);
{
fstream myfile("C:\Data\file(i).dat")
.....
}
In other words, is there a way to insert the "i" variable into the filename?
Thank you for your insights.
dduardo
Jun25-04, 09:41 AM
You can save the string inside myfile in a character array. Then you can change the number by doing file[where ever it is] = 3. You'll have to name the file 01, 02, 03, etc because you'll be dealing with double digits.
The other option is to use string concatentation. You can either do it the C or the C++ way. Using the C way you would include string.h and use the function called strcat(). If you do it the C++ way you would include string and use the member function of the string class called append().
Thanks. I ended up solving the problem with strcat. For some weird reasons my compiler (MS VC++ 6) does not recognize string as a variable type, even though I #included string.h. All paths are correct, I am baffled as to why this is not working. Fortunately the array of char thing worked just fine.
dduardo
Jun25-04, 01:31 PM
The string datatype doesn't work because you need to use #include<string> which is the STL library for C++. #include<string.h> is the C library. When using STL you also should put after the includes: "using namespace std;". That way you you don't need to do this when you want to declare a new string: "std::string mystring;"
[edit] Muzza, your right, you can use the overloaded operator (+) to contatenate multiple strings. For example, this would work:
#include<iostream>
#include<string>
using namespace std;
int main( int argc, char **argv) {
string str1 = "Hello";
string str2 = " ";
string str3 = "World!";
cout << str1 + str2 + str3 << endl;
}
The output being:
Hello World!
So no .h? Well, now that the strings are working it is much easier. Thank you.
[edit] Muzza, your right, you can use the overloaded operator (+) to contatenate multiple strings. For example, this would work:
Ack, why do people always manage to see the posts I delete ;) Anyway, I knew about string concatenation (in fact, I used it in my deleted post ;)), but using + to concatenate an /integer/ to an STL string doesn't seem to work (or so it appeared, my test program segfaulted).
vBulletin® v3.8.7, Copyright ©2000-2012, vBulletin Solutions, Inc.