Home c++ Read file line by line

Read file line by line




You need to open the file and read it line by line, that is, take the first line, enter it into a variable, do certain operations with it, then take the second, etc.

Answer 1, authority 100%

ifstream file (fileName); // create an istream stream object named file
            // which is initialized with fileName,
            // function file.open () is called;
 string str; // string variable for string
while (getline (file, str)) // getline (istream & amp; is, string & amp; s, char c = '\ n'), read from stream is, into string s for now
{// will not encounter the character c (without this character until a new line)
            // returns its istream object, the condition of the iostate flag is checked in the condition, the value of this flag will be false if it reaches the end of the file, or there will be an input or read type error
   fncn (str); // call the required function for the resulting string

Answer 2, authority 100%

here is the code not taken out of context

# include & lt; iostream & gt;
#include & lt; string & gt; // connect strings
#include & lt; fstream & gt; // include files
using namespace std; // use the standard namespace
int main () {
  string s; // we will put the read lines here
  ifstream file ("C: \\ PriceList.dat"); // the file from which we read (for linux the path will look different)
  while (getline (file, s)) {// until the end of the file is reached, put the next line in the variable (s)
    cout & lt; & lt; s & lt; & lt; endl; // display
    s + = "+"; // do something with the line, for example, I add a plus sign at the end of each line
cout & lt; & lt; s & lt; & lt; endl; // and again display the modified string (without writing it to a file)
  file.close (); // be sure to close the file so as not to damage it
  return 0;

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions