Jun 16, 2013 at 10:48pm UTC
#include <iostream>
#include <fstream>
#include <string>
//---------------------------------------------------------------
using namespace std;
//---------------------------------------------------------------
struct Mokinys
{
string pav;
string dalykas;
};
//---------------------------------------------------------------
const char CDfv[] = "duomenys.txt";
const char CRfv[] = "rezultatai.txt";
const int CMax = 30;
//---------------------------------------------------------------
void SkaitytiPav(ifstream & fd, int & n, Mokinys A[]);
void SkaitytiKlase(ifstream & fd, int & n, Mokinys A[]);
void Spausdinti(int n, Mokinys A[], string comment);
//---------------------------------------------------------------
void SkaitytiPav(ifstream & fd, int & n, Mokinys A[])
{
char eil[26];
fd >> n;
fd.ignore();
for (int i = 1; i <= n; i++)
{
fd.get(eil, 26);
A[i].pav = eil;
A[i].dalykas = "";
fd.ignore(80, 'n');
}
}
void SkaitytiKlase(ifstream & fd, int & n, Mokinys A[])
{
char eil[26];
fd >> n;
fd.ignore();
for (int i = 1; i <= n; i++)
{
fd.get(eil, 26);
A[i].pav = eil;
fd >> ws;
getline(fd, A[i].dalykas);
}
}
void Spausdinti(int n, Mokinys A[], string comment)
{
ofstream fr(CRfv, ios::app);
fr << comment << endl;
fr << "----------------------------------------" << endl;
fr << " Mokinys Dalykas" << endl;
fr << "----------------------------------------" << endl;
for (int i = 1; i <= n; i++)
fr << left << A[i].pav << A[i].dalykas << endl;
fr << "----------------------------------------" << endl << endl;
fr.close();
}
int main()
{
Mokinys Klase[CMax]; int n;
Mokinys Ate[CMax]; int m;
Mokinys Nauji[CMax]; int k;
ofstream fr(CRfv);
fr.close();
ifstream fd(CDfv);
SkaitytiPav(fd, m, Ate);
SkaitytiKlase(fd, k, Nauji);
SkaitytiKlase(fd, n, Klase); // <- here's the problem
fd.close();
Spausdinti(n, Klase, "Klases sarasas");
Spausdinti(k, Nauji, "Naujoku sarasas");
return 0;
}
I wrote a few functions to read data from duomenys.txt file but program is reading files only with 'SkaitytiPav' function.
Jun 17, 2013 at 9:40am UTC
for (int i = 1 ; i <= n; i++) // wrong
C/C++ arrays start with 0, hence the last available index of an array is one smaller then the array size. The correct loop looks like this:
for (int i = 0; i < n; i++) // ok, starts with 0
[EDIT]
fd.ignore(80, 'n' ); // do you really want to ignore until 'n' not '\n'?
1 2
fd >> ws; // are you sure that there is no ignore() necessary?
getline(fd, A[i].dalykas);
[/EDIT]
Last edited on Jun 17, 2013 at 10:05am UTC
Jun 18, 2013 at 4:31pm UTC
Thank you for your help.:) The reason why the programme didn't work was that I wrote 'n' instead of '\n' in fd.ignore() function. 'fd >> ws' and array numbering didn't interfere.
Last edited on Jun 18, 2013 at 4:34pm UTC