I’m working on a project which requires a large list of words, each to be numbered (No, this doesn’t have to do with hacking, I’m making a random poetry engine). I was just wondering if there was any program that would take a text file and add a number to each line just so I don’t have to do it all by hand, or if not, could someone help me figure out how to make one in C/C++.
Word does it. So does NoteTab.
Well, I’m the hacker who’s going to help you.
In C++, 'cause C isn’t as nice for this kind of work:
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main(int argc, char *argv[])
{
vector<string> v;
string s;
ifstream file;
if (argc < 2) {
cout << "usage: linenum file" << endl;
return 1;
}
if (!file.open(argv[1])) {
cout << "Can't open file " << argv[1] << endl;
return 1;
}
while (s << file)
v.push_back(s);
for (int i = 0; i < v.size(); ++i)
cout << i + 1 << " : " << v*;
file.close();
return 0;
}
You can download Note Tab for free here.
Jeez. There’s no reason to use C++ for such a simple job:
perl -pi -e 'print "$.: "' < input.txt > numbered.txt
Easy as pie.
Ewww, perl.
awk '{ print NR " " $0 }' < source_file > destination_file
Not everyone is lucky enough to have a Perl or awk interpreter. I assumed the OP just had a C++ compiler (probably one of the MS variants) and was running a Win32 system with none of the stuff that makes a *nix command line so nice.
If it had been my system (Fedora Core 1, at the moment), I’d have used awk out of force of habit.
Oh, and my code is broken.
Replace the ‘while (s << file)’ with ‘while (getline(file, s))’ and the ‘cout << i + 1 << " : " << v*;’ with ‘cout << i + 1 << " : " << v* << endl;’ and it should all work fine.
That’s what you get for using C++ to do Perl’s job.
How about a grep:
grep "" -n input.txt > output.txt
C++, perl, and awk all seem like overkill when plain old cat’s -n flag will do the trick.
cat -n < input.txt > output.txt
I think John T. Conklin wins the prize. Although to be even more pedantic, don’t actually need the input redirection.
Yep, John wins. I had forgotten about that option to cat.