Thursday, July 9, 2009

How do i write a c++ program that reads the top line of a text tile till the newline charecter?

I need to write a c++ program, that reads the top line of a txt file stopping at the end of the line.





i tried:





#include %26lt;iostream.h%26gt;


#include %26lt;fstream.h%26gt;


#include %26lt;stdio.h%26gt;





void main()


{


int i;


char l[20];


char tem='0';


ifstream example("d:\\test2.txt");





for(i=0; tem!=char(10) %26amp;%26amp; !example.eof();i++)


{


example%26gt;%26gt;tem;





if(tem!=char(10))


{


l[i] = tem;


}


}





for(i=0; i%26lt;6; i++)


{


cout%26lt;%26lt;l[i];


}


cout%26lt;%26lt;endl;





}





But the result is just 123456 even though my file says:


"123





456"





What am i doing wrong/ what should i do?

How do i write a c++ program that reads the top line of a text tile till the newline charecter?
The bug is the line:





example%26gt;%26gt;tem;





The "%26gt;%26gt;" operator seems to ignore the newlines so, do this instead:





tem = example.get();





But the code can be greatly simplified once you think about how C++ (but not C) can deal with lines as whole strings instead of as arrays of characters. Also, C++ has standard methods in string/fstream that can read files line-by-line. These two realizations result in this simplified version of what you're trying to do:





#include %26lt;iostream%26gt;


#include %26lt;fstream%26gt;


#include %26lt;string%26gt;





using namespace std;





int main ()


{


    ifstream file("test2.txt");





    // see http://cppreference.com/cppstring/getlin...


    string line;


    getline( file, line);


    cout %26lt;%26lt; line;





    file.close();


}








Since you're learning, a few nick picks about your code if you don't mind:





1) "void main()" is not standard C++, use "int main()" instead, according to the creator of C++:


http://www.research.att.com/~bs/bs_faq2....





2) stdio.h is C, not C++. stdio.h lets you do C-style printf's (among other things) instead of cout %26lt;%26lt; (which is provided by iostream) so you don't need to include stdio.h here.





3) Putting a ".h" at the end of the iostream and fstream includes (I believe?) uses the deprecated versions of those libraries. You're better off omitting the ".h" Unless you're using old compiler/libraries that don't have the newer versions.
Reply:try using


'\n' instead of char(10)


or just 10








anyways if you're in windows and you made your file with notepad (and others..) your new lines would be made of two caracters carriage return and line feed \r\n, so your l would have an extra \r inside.


No comments:

Post a Comment