0

This is how I get the name of the file from the command line and open a file and save the content of the file line by line to a string. All the procedures works fine except three empty spaces at the beginning of the file. Is anyone can say why these empty spaces occurred and how can I ignore them?

string filename = "input.txt";

char *a=new char[filename.size()+1];
a[filename.size()]=0;
memcpy(a,filename.c_str(),filename.size());

ifstream fin(a);
if(!fin.good()){
    cout<<" = File does not exist ->> No File for reading\n";
    exit(1);
}
string s;
while(!fin.eof()){
    string tmp;
    getline(fin,tmp);
    s.append(tmp);
    if(s[s.size()-1] == '.')
    {
        //Do nothing
    }
    else
    {
        s.append(" ");
    }
        cout<<s<<endl;
Bernard
  • 4,240
  • 18
  • 55
  • 88

1 Answers1

1

The most probable cause is that your file is encoded in something else than ASCII. It contains a bunch of unprintable bytes and the string you on the screen is the result of your terminal interpreting those bytes. To confirm this, print the size of s after the reading is done. It should be larger than the number of characters you see on the screen.

Other issues:

string filename = "input.txt";
char *a=new char[filename.size()+1];
a[filename.size()]=0;
memcpy(a,filename.c_str(),filename.size());
ifstream fin(a);

is quite an overzealous way to go about it. Just write ifstream fin(a.c_str());, or simply ifstream fin(a); in C++11.

Next,

while(!fin.eof()){

is almost surely a bug. eof() does not tell if you the next read will succeed, only whether the last one reached eof or not. Using it this way will tipically result in last line seemingly being read twice.

Always, always, check for success of a read operation before you use the result. That's idiomatically done by putting getline in the loop condition: while (getline(fin, tmp))

Community
  • 1
  • 1
jrok
  • 54,456
  • 9
  • 109
  • 141
  • My file is a notepad and I typed inside it myself, even if the file is empty I get three question marks at the beginning.... I change it to c_str() and eof() but still I get same thing. – Bernard Nov 04 '13 at 17:32
  • 1
    @Bernard Show a complete compilable program then ([SSCCE](http://sscce.org)), along with the contents of the file. – jrok Nov 04 '13 at 17:48
  • That was complete program but you only need to put it in int main() { and } and put a file in same directory to run this. – Bernard Nov 04 '13 at 17:53
  • 1
    @Bernard Your issue is [BOM](http://en.wikipedia.org/wiki/Byte_order_mark), I'd say. The fact that you "typed it in notepad" is... not very relevant. As said, you've got it encoded in Unicode or UTF-8. Select "Ansi" from the dropdown list when you save the file. – jrok Nov 04 '13 at 18:40