What happens if at cin>>ch the user types more than 9 characters?
What happens if the user type some spaces ?
If you want to use fixed buffers and null-terminates C strings, you have always to take care of the space and of the null-termination.
Also, to "pause at the and", yopu must ensure that no unread input is present.
The way to do that is discard every residual input after the read of the string.
#include <iostream>
#include <fstream>
#include <iomanip>
#include <cstring>
#include <limits>
int main()
{
using namespace std;
const unsigned BUFFSZ=9;
char ch[BUFFSZ+1];
memset(ch,0,sizeof(char)*(BUFFSZ+1));
char c=0;
fstream f;
f.open("text",f.out);
cout<<"Enter a string :";
cin >> std::setw(BUFFSZ) >> ch;
cin.ignore(numeric_limits<streamsize>::max(),'\n');
f<<ch;
f.close();
f.open("text",f.in);
while(f.get(c))
{
cout<<c;
}
f.close();
cin.get();
return 0;
}
The above program is safe, but reads the string up to the first space and up to 9 character (note the ch is 9+1 since there must be the space for the null character string terminator.
Note that
f.get(c)
is used in the loop condition: in your original loop, when you read the last character with
f.get(c)
, the file is still "
good", so you make another turn,
f.get(c)
fails, (making the file
bad)and
c
is left the the previous character (hence the repetition in printing)
If you want to be more safe, you should use
std::string
that uses dynamic memory to accommodate whatever length:
#include <iostream>
#include <fstream>
#include <string>
#include <limits>
int main()
{
using namespace std;
string ch; char c=0;
fstream f;
f.open("text",f.out);
cout<<"Enter a string :";
getline(cin, ch);
f<<ch;
f.close();
f.open("text",f.in);
while(f.get(c))
{
cout<<c;
}
f.close();
cin.get();
return 0;
}
There is no more need to take care about the length, the entered text can contain spaces and the line is read to the end (so no cleanup is required).