hi...
got a programming assignment which really makes my brain bleed...all threads gives answers on how to access a text file and display text from that source. what i really need is the code in which i would get the text from every single line inside the text file. for example, the text file's data is like this:

109-2033, Johnny Gil
109-2034, Johnny Depp
109-2035, Johnny John
109-2036, Johnny doe

i need the code which will give me this output:

line 1: 109-2033, Johnny Gil
line 2: 109-2034, Johnny Depp
line 3: 109-2035, Johnny John
line 4: 109-2036, Johnny doe

i hope someone could help me out asAp...i'll be forever grateful...thanks

Dani AI

Generated

As described, the goal is to read every line from a text file and print it with a line number. As hinted, use std::getline. As suggested, keep an incremental counter. A compact, robust pattern looks like this:

#include <iostream>
#include <fstream>
#include <string>

int main() {
    std::ifstream file("data.txt");
    if (!file) {
        std::cerr << "Error: cannot open data.txt\n";
        return 1;
    }

    std::string line;
    int line_no = 1;
    while (std::getline(file, line)) {
        if (!line.empty() && line.back() == '\r') line.pop_back(); // trim Windows CR
        std::cout << "line " << line_no++ << ": " << line << '\n';
    }
}

Notes and common pitfalls:

  • Always check the file opened successfully before reading.
  • Use the while (std::getline(...)) pattern so empty lines are read correctly. If you want to skip empty lines but still count them differently, handle that explicitly.
  • If the file was created on Windows, lines may end with \r\n; trimming a trailing \r ensures the output looks correct.
  • If the program previously used extraction with >>, consume the leftover newline before calling std::getline (for example with std::getline to read and discard the remainder of that line).

If you need the lines later, push each line into a std::vector<std::string> and iterate over it to print with indexes. For reference on the non-member std::getline utility, see the documentation at std::getline.

Recommended Answers

All 2 Replies

What have you tried so far?

Hint: use the getline function

Member Avatar for Member #46692

And an incremental counter.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.