1

I would like to output a file which is readable like database concept. What I expect is:

Name[10]  ContactNo[15]  GENDER[10]
====================================
Johnny    +60123456789   MALE      
Emily     +69876543210   FEMALE    
Jason     +61535648979   MALE      

And i attempt to do this with:

char name[10],contact[15],gender[10];

//user input here//

ofstream myfile("contact.txt");
myfile>>name>>contact>>gender;

but all string in output file is concatenate without any space. Any idea that i can do that? I try to do this in order for when i read data from file with exactly width and put them into variable, is it a wrong concept? Or any suggestion?

crossRT
  • 616
  • 4
  • 12
  • 26
  • Set adjustfield and width on output stream. E.g. myfile.width(100); – user2672165 Aug 21 '13 at 10:07
  • You should look at [`std::string`](http://en.cppreference.com/w/cpp/string/basic_string) and [`std::setw`](http://en.cppreference.com/w/cpp/io/manip/setw). – BoBTFish Aug 21 '13 at 10:08

3 Answers3

2

A combination of stream manipulators std::setw and std::setfill will do what you want:

myfile << std::setfill(' ') << std::left
       << std::setw(10) << name
       << std::setw(15) << contact
       << std::setw(10) << gender;

setfill lets you specify the character used for filling. std::left, std::internal and std::right specify where the fill characters go.

Hashbrown
  • 12,091
  • 8
  • 72
  • 95
jrok
  • 54,456
  • 9
  • 109
  • 141
0

I would include <stdio.h> and use printf()

printf ( "%10s %15s %10s\n", name, contact, gender );

That should get you what you want.

BoBTFish
  • 19,167
  • 3
  • 49
  • 76
amrith
  • 953
  • 6
  • 17
0

I would recommend you to use the symbol \t between the values. \t insert a tab. Then, you have to write:

myfile>>name>>"\t">>contact>>"\t">>gender;
Stratford
  • 325
  • 1
  • 2
  • 11
  • 1
    I would not recommend this, `'\t'` is a pain in the bum. Amongst other things, consider if the difference in length between two lines is more than 4 characters (or 8, or whatever, which is another issue). – BoBTFish Aug 21 '13 at 10:11