Need some help, writing a program that will read the text from a file, but when it prints it out to the console each new line from the file should be numbered.
example
file1
a
b
c
console print out should be
1: a
2: b
3: c
and if a second files has more lines the code should be adding a new number each time.
I tried a few things but I can only get my code to print the same number if anyone can help let me know
int main()
{
//variables
ifstream data_store;
string file_name;
string line;
//asks user to enter a name of a file
cout << "Enter filename" << endl;
//user will enter a name of a file.
cin >> file_name;
//open the file
data_store.open(file_name.c_str());
//loop for each line
while (!data_store.eof())
{
//print out lines from text files
getline(data_store, line);
cout << "1: "<< line << endl;
}
//close file
data_store.close();
Edit:
Ahhh, getting tired... Should go for a sleep... You could use the getline method of ifstream or you could add a counter to your while loop.
For reference check: http://www.cplusplus.com/reference/fstream/ifstream/
As NT3 stated below
In your print line, you have std::cout << "1: " << line << std::endl. When you add to the value, the line number doesn't change (i.e. its always 1). Instead, try something like this:
1 2 3 4 5
int i = 0;
while (!data_store.eof()) {
std::getline(data_store, line);
std::cout << ++i << ": " << line << std::endl;
}
What this does is it gets you a number "i", and adds one to it every time you loop through. This should give you the result you want.
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
usingnamespace std;
int main()
{
/*
Prefer definiing variables close to the point of their first use
//variables
ifstream data_store;
string file_name;
string line;
*/
string file_name;
//asks user to enter a name of a file
//cout << "Enter filename" << endl;
cout << "Enter filename\n" ; // cout (tied to cin), is flushed before input
//user will enter a name of a file.
cin >> file_name;
//open the file
// data_store.open(file_name.c_str());
// let the constructor open it for us
ifstream data_store(file_name) ;
// the line number is an integer
int line_number = 0 ;
// and the line is a string
std::string line ;
//loop for each line
// while (!data_store.eof())
// checking for failure before attempted input leads to a subtle error
// {
// getline(data_store, line) ; // what happens if this fails?
// we don't check for failure and proceed as if we had successfully read a line
// ...
// }
while( getline(data_store, line) ) // this is canonical
{
//print out he line just read along with the line number
cout << setw(4) // we expect at most 9999 lines
<< ++line_number // we print line numbers starting at one
<< ". "
<< line << /*endl*/ '\n' ; // there is no need to force a gratituos flush of cout
}
//close file
// data_store.close();
// the destructor will close it for us
// return 0;
// return 0 is implied when we reach the end of main()
}