As the name suggests, this simple function adds line numbering to a .txt file. Download(zip).
//Knowledgedump.org - Function for adding line numbers to a .txt file. Writes to "filename_numbered.txt".
#ifndef ADD_LINE_NUMBERS_H //Include guard
#define ADD_LINE_NUMBERS_H
#include <iostream>
#include <fstream>
#include <string>
int add_line_numbers(std::string filename) { //Filename without .txt
std::fstream stream;
std::string str, full;
int line_number = 1;
//Read from text-file, save numbered content in string "full"
stream.open(filename + ".txt", std::fstream::in); //Open stream for reading of file
if (stream.is_open()) {
while (std::getline(stream, str)) { //getline return interpreted as true, as long as it receives input
full += std::to_string(line_number) + ": " + str + "\n"; //Numbering layout is 1: ... 2: ... etc.
++line_number;
}
if(!full.empty()) full.pop_back(); //Remove extra '\n' character
stream.close();
}
else {
std::cout << "Couldn't open input filestream." << std::endl;
return 0;
}
//Write to text-file "filename_numbered.txt"
stream.open(filename + "_numbered.txt", std::fstream::out);
if (stream.is_open()) {
stream << full;
stream.close();
}
else {
std::cout << "Couldn't open output filestream." << std::endl;
}
return line_number - 1; //Returns number of lines in text-file.
}
#endif //Include guard
//Knowledgedump.org - Example file.
#include "add_line_numbers.h"
int main() {
std::string input_txt = "test";
//Add line numbers to text file "test" and print number of lines to console.
std::cout << add_line_numbers(input_txt) << std::endl;
return 0;
}
This text file contains several lines
1: This 2: text 3: file 4: 5: 6: contains 7: 8: several 9: lines