I have a file records.txt
that contains the following text:
John Smith Sales 555-1234
Mary Jones Wages 555-9876
Paul Harris Accts 555-4321
I've copied the following code from C++ Programming by Mike McGrath into a file format.cpp
to read the data in records.txt
:
#include <fstream>
#include <string>
#include <iostream>
using namespace std;
int main()
{
const int RANGE = 12;
string tab[RANGE];
int i = 0, j = 0;
ifstream reader("records.txt");
if (!reader)
{
cout << "Error opening input file" << endl;
return -1;
}
while (!reader.eof())
{
if ((i + 1) % 4 == 0)
getline(reader, tab[i++], '\n');
else
getline(reader, tab[i++], '\t');
}
reader.close();
i = 0;
while (i < RANGE)
{
cout << endl << "Record Number: " << ++j << endl;
cout << "Forename: " << tab[i++] << endl;
cout << "Surname: " << tab[i++] << endl;
cout << "Daprtment: " << tab[i++] << endl;
cout << "Telephone: " << tab[i++] << endl;
}
return 0;
}
Now, in my .emacs
file, I have tabs automatically converted to spaces in all my files, per the following command:
(setq-default indent-tabs-mode nil)
So when I compile and run format.out
, I get the following output:
$ ./format.out
Record Number: 1
Forename: John Smith Sales 555-1234
Mary Jones Wages 555-9876
Paul Harris Accts 555-4321
Surname:
Daprtment:
Telephone:
Record Number: 2
Forename:
Surname:
Daprtment:
Telephone:
Record Number: 3
Forename:
Surname:
Daprtment:
Telephone:
This isn't what I want. What I want is for each tab-separated item to be printed after its corresponding label.
So I go into emacs
and enter the following command to convert spaces to tabs within records.txt
:
M-x tabify
But now when I re-run my script, I get a seg fault:
$ ./format.out
Segmentation fault (core dumped)
Why is this, and what can I do to fix it? (Or, if a reason isn't apparent, what can I do to investigate this further?)
There seems to be a problem in my c++
code, not the file itself, because when I read records.txt
in python
, I can see that it is as expected:
In [1]: with open('records.txt') as f:
...: x = f.readlines()
...:
In [2]: x
Out[2]:
['John\tSmith\tSales\t555-1234\n',
'Mary\tJones\tWages\t555-9876\n',
'Paul\tHarris\tAccts\t555-4321\n']