-
Spliting among 2 files
I have a file of 10 different names. It is read into a program and the names are split into 2 files.
Here is the code:
Code:
#include <iostream.h>
#include <stdlib.h>
#include <vector>
#include <fstream>
#include <string>
int main()
{
ifstream names;
names.open ("D:\\Documents and Settings\\Suchy\\Desktop\\names.txt");
if (! names)
{
cout << "File not opened" << endl;
}
int amount = 0;
string loaded_names; // holds names form file
for (int i = 0 ; names >> loaded_names ; i++)
{
amount ++ ; // counts # of names in file
}
cout << "There are " << amount << " names in the file" << endl;
int half = amount/2;
cout << "Output1 will get " << half << " files and Output2 will get "
<< half << " files " << endl;
ofstream Output1 , Output2;
Output1.open ("D:\\Documents and Settings\\Suchy\\Desktop\\Output1.txt");
for (int i = 0 ; i < half ; i ++)
{
Output1 << loaded_names << " ";
}
Output2.open ("D:\\Documents and Settings\\Suchy\\Desktop\\Output2.txt");
for (int i = amount ; i > half ; i --)
{
Output2 << loaded_names << " ";
}
system("PAUSE");
return 0;
}
The problem is that only the last name in the file (Frank is transfered into the 2 Output files. (They look like this after program runs: Frank Frank Frank Frank Frank )
Why is it that only the last name gets distributed?
-
Because these lines:
Output1 << loaded_names << " ";
Output2 << loaded_names << " ";
Just output the same string over and over and over. loaded_names isn't changing inside those loops.
-
>> #include <iostream.h>
Is there a reason you're using the non-standard header here, but not for the other headers? Also, the std namespace is missing, which you should need for string and ofstream anyway. Even if that code somehow compiles for you, you should consider correcting it to proper, standard C++ so that others can compile and run your code easily and help you with your issues.
-
Code:
if (! names)
{
cout << "File not opened" << endl;
}
Do you really wish to continue if this happens?
-
Code:
for (int i = 0 ; names >> loaded_names ; i++)
{
amount ++ ; // counts # of names in file
}
This only stores a single name in the variable loaded_names (the last name from the file is what stays in loaded_names after the loop is done). You need a container (vector perhaps) to store all occurances of the various names that you will read in from the file.
-
Thanks for the tips, as for all the #include <iostream.h> I will get a compile error in Dev 4 when I ommit the .h on some libraries, but not on all of them. I also use this file for practice, before I worked on vectors so I just leave in all the #includes even If I am not currently using one, ex vectors in this case..
-
You probably need a new copy of Dev-C++... 4.9.9.2 is the most recent release. You should also have using namespace std or prefix stuff in the standard library with std::.