Reading and writing TXT file

Hello!
Yet another question of these, and trust me, i've been trying all solutions on the page regarding this topic, but nothing works.

MY ASSIGNMENT
I have a text file (.TXT) which i have already put into the Xcode "Derived Data" folder (yup using Xcode for mac). The txt file consists of 1 column, with 8 lines.

Ie:

Headline:
word 1
word 2
.
.
.
word 8

i want to ifstream the file above, read how many lines, and PRINT all the lines. Bare in mind, the words are not on 1 line, they have each of their own line. They are of different lengths, and im not supposed to know that there are 8 lines.

Should i use vectors, arrays....


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
 #include <iostream>
#include <fstream>
#include <string>
#include <vector>

using namespace std;


int main ()
{
    ifstream indFil;
    indFil.open("dosmer.txt");
    string elementer,linjer;
    
    
    //kontrollerer fejl
    if (indFil.fail()) {
        cerr << "Opening file failed!" << endl;
        exit(1);
    }
    
    int count = 0;
    
    //Read how many lines there are in the file (WORKS!)
    while (!indFil.eof()) {
        indFil>>elementer;
        count++;
    }
    
    cout << count << " lines found! " << endl;
    
    
    // now print what's in these lines
    while (indFil >> linjer){
        cout << linjer << endl;
    }
    
    indFil.close();
    
   
return 0;
}


please give me some examples of how to do it. thanks in advance.
Last edited on
closed account (SECMoG1T)
Use getline () instead
like this: (?)
1
2
3
4
5
6
7
8
9
10
11
// print the elements in the file
    cout << "Following items has to be bought:" << endl;
    cout << "=========================" << endl;
    
    while (! indFil.eof()) {
        indFil.getline(&linjer, sizeof(linjer));
        cout << linjer << endl;
    }
    
    return 0;


my output still only reads the numbers of lines, that the working "while" loop in "op" shows. non of the items thats in the txt. file
closed account (SECMoG1T)
Here is the idea

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
  ifstream in ("dosmer.txt");
  std::size_t  lines=0;
  std::vector<std::string> my_dosmer;
  std::string temp;

  if(! in)
   { std::cout <<" reading failed"; exit (0); }

  while(getline (in, temp, '\n'))
   {
      my_dosmer.push_back (temp);
      ++lines;
   }

   in.close ();

   std::cout <<" line count  :"<<lines <<std::endl;
   std::cout <<" content \n";

   for (const auto& str : my_dosmer)
      {
        std::cout <<str <<std::endl;
      }

  



The reason your code from line 33 dint work is because your stream was already at EOF , you could also solve your problem by closing your stream, clear the error state then reopen your file again.
Last edited on
@andy1992 i thank you for you help, but i cant get it to work. take a look at my code so far.

initializes:
1
2
3
4
ifstream indFil;
    indFil.open("dosmer.txt");
    string elementer;
    vector<string> linjer;


then all the code that works, and then yours:
1
2
3
4
5
6
    for (const auto& str : linjer) {
        cout << str << endl;
    }
    
    return 0;
}


btw, i did the indFil.close().
closed account (SECMoG1T)
Please post your whole code so that I can check it out.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#include <iostream>
#include <fstream>
#include <string>
#include <vector>

using namespace std;


int main ()
{
    ifstream indFil;
    indFil.open("dosmer.txt");
    string elementer;
    vector<string> linjer;
    
    
    //error check and msg
    if (indFil.fail()) {
        cerr << "Åbning af fil mislykkedes!" << endl;
        exit(1);
    }
    
    int count = 0;
    
    //Print how many lines are in text file
    while (!indFil.eof()) {
        indFil>>elementer;
        count++;
    }
    
    cout << count << " linjer fundet! " << endl;
    cout << endl;
    
    indFil.close();
    
    // print elements in file preceded by headline and ==== line
    cout << "Følgende ting skal købes:" << endl;
    cout << "=========================" << endl;
    
    for (const auto& str : linjer) {
        cout << str << endl;
    }
    
    return 0;
}
closed account (SECMoG1T)
Well just a simple error , in your loop on line 26:-
1. You'll need to add elementer into the vector "linjer"
linjer.push_back (elementer); /// add these on line 27

2. The reason I decided to use getline is because what if one line could have a string like
"My name" this will be a logical bug , your count would register these words as different
lines

3.
print elements in file preceded by headline and ==== line

If your file contains a headline you'll need to ignore the first reading inside
The loop.
like this?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#include <iostream>
#include <fstream>
#include <string>
#include <vector>

using namespace std;


int main ()
{
    ifstream indFil;
    indFil.open("dosmer.txt");
    string elementer;
    vector<string> linjer;
    
    
    //kontrollerer fejl
    if (indFil.fail()) {
        linjer.push_back(elementer);
        cerr << "Åbning af fil mislykkedes!" << endl;
        exit(1);
    }
    
    int count = 0;
    
    //Læs hvor mange linjer der er i filen
    while (!indFil.eof()) {
        indFil>>elementer;
        count++;
    }
    
    cout << count << " linjer fundet! " << endl;
    cout << "\n";
    
    indFil.close();
    
    // print elementer i filen
    cout << "Følgende ting skal købes:" << endl;
    cout << "=========================" << endl;
    
    for (const auto& str : linjer) {
        cout << str << endl;
    }
    
    indFil.close();
    
    return 0;
}


i dont see why i should put linjer.push_back (elementer); in the error controle? O.o

just fyi. my text file looks like this:

Indkoebsseddel:
Juice
Aebler
Bananer
Maelk
Bananer
Gaer
Havregryn
Last edited on
closed account (SECMoG1T)
Well line 27 shouldn't be in your error checker, should be like these:-
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
 #include <iostream>
 #include <fstream> 
 #include <string>
 #include <vector>
 
  using namespace std;

  int main () 
   {
      ifstream indFil; 
      indFil.open("dosmer.txt");

     string elementer, headline; 
     vector<string> linjer; 

    //kontrollerer fejl
    if (indFil.fail())
     {  cerr << "Åbning af fil mislykkedes!" << endl; exit(1); }

    int count = 0; 

    //Læs hvor mange linjer der er i filen 
    
    indFil>> headline; /// ignore your headline
    while (!indFil.eof()) 
     { 
       indFil>>elementer; count++;  
       linjer.push_back(elementer);
      }

      cout << count << " linjer fundet! " << endl;
      cout << "\n"; 
  
      indFil.close();

      // print elementer i filen
      cout << "Følgende ting skal købes:" << endl; 
      cout << "=========================" << endl; 

     for (const auto& str : linjer)
      { 
         cout << str << endl; 
      } 

     /* the above loop is equivalent to
      *  for (unsigned int j=0; j <linjer.size (); j++)
      *    {
      *       cout <<linjer [j]<<endl;
      *    }
      */

      return 0;
  }


Hope that works.
Last edited on
it fuckin works!! thank YOU Andy..
I actually recommend a few changes:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#include <iostream>
#include <fstream>
#include <string>
#include <vector>

using namespace std;

int main ()
{
   ifstream indFil("dosmer.txt"); // Note the open() function not needed.

   string elementer, headline;
   vector<string> linjer;

   //kontrollerer fejl
   if (indFil.fail())
   {
      cerr << "Åbning af fil mislykkedes!" << endl;
      return(1);  // Note this is main() a return is preferred over exit(). 
   }

   //Læs hvor mange linjer der er i filen

   //indFil >> headline; /// ignore your headline
   getline(indFil, headline); // Note I recommend getline(), no worry about spaces.
   
   while(indFil >> elementer)  // Note using the actual read to control the loop.
   {
      linjer.push_back(elementer);
   }
   
   // Note count no longer needed, a vector knows it's size.
   cout << linjer.size() << " linjer fundet! " << endl;
   cout << "\n";

   // indFil.close(); // Note this close is not needed, just let the destructor do it's job.

   // print elementer i filen
   cout << "Følgende ting skal købes:" << endl;
   cout << "=========================" << endl;

   for (const auto& str : linjer)
   {
      cout << str << endl;
   }

   /* the above loop is equivalent to
    *  for (unsigned int j=0; j <linjer.size (); j++)
    *    {
    *       cout <<linjer [j]<<endl;
    *    }
    */

   return 0;
}


You should strive to avoid the exit() function whenever possible in a C++ program. This C function doesn't understand C++ classes and it's use can result in data corruption.
Topic archived. No new replies allowed.