LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (http://www.linuxquestions.org/questions/programming-9/)
-   -   C++ Generating code (http://www.linuxquestions.org/questions/programming-9/c-generating-code-514073/)

balgaltz 12-27-2006 12:29 PM

C++ Generating code
 
#include <sstream>
#include <fstream>
#include <vector>
#include <iterator>
#include <algorithm>

using namespace std;

void put_into_vector( ifstream& ifs, vector<int>& v )
{
string s;
getline( ifs, s );
istringstream iss( s );
// not the fastest method ...
copy( istream_iterator<int>( iss ), istream_iterator<int>(), back_inserter( v ) );
}

int main()
{
vector<int> line_1, line_2;

ifstream ifs( "C://data.txt" );

put_into_vector( ifs, line_1 );
put_into_vector( ifs, line_2 );

}

Is there a way to read automatically each line of the data.txt depending on how many lines the file has?

I can get the number of lines that it has with:

int line_count = 0;
char ch;

ifstream iFile("c:/data.txt");

if (! iFile)
{
cout << "Error opening input file" << endl;
system("pause");
return -1;
}

while (iFile.get(ch))
{
switch (ch) {
case '\n':
line_count++;
break; }
cout << line_count;

Thanks in advance :)

indienick 12-28-2006 10:16 PM

You could always test to make sure that you're not at the EOF. I don't know how to do this in C or C++, but it's done like so in a few other languages:
Code:

Java
java.util.Scanner s = new java.util.Scanner(new java.io.File("file.txt"));
String str;
while(s.hasNext() == true) {
  System.out.println(s.nextLine());
}

BASIC
OPEN "file.txt" FOR READ AS #1
WHILE NOT EOF(1)
  INPUT #1, s$
  PRINT s$
WEND
CLOSE #1

Perl
open(INFILE, "file.txt");
while(<INFILE>) {
  print("$_\n");
}
close(INFILE);

Lisp
(with-open-file (istream #p"file.txt" :direction input)
  (format t "~a~&" (read-line istream)))

I hope this helps in some way. :)

alunduil 12-28-2006 10:18 PM

It's similar in C++ as well:

Code:

if (!fstream.eof())
{
    // Do Stuff Here.
}

Regards,

Alunduil

indienick 12-28-2006 10:21 PM

Good to know. :)


All times are GMT -5. The time now is 12:58 PM.