I/O user friendly file name
Jul 14, 2015 at 6:14pm UTC
Hi I'm new to C++.
I was practicing some programs. And I was wondering for the follwing program,
is it possible to name the output text file on users choice?
like lets say if the user puts his name Luigi, can I make the output text name as "Luigi.txt"?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
string name;
string fileName;
int age;
cout<<"Enter name: " ;
cin >> name;
cout<<"Enter age: " ;
cin >> age;
fileName = name+".txt" ;
ofstream output;
output.open(fileName);
output<<"Name: " <<name
<<"\nAge: " <<age;
output.close();
Jul 14, 2015 at 6:22pm UTC
Sure, but you must follow the cardinal rule of user input:
All user input is terminated when the user presses ENTER
To get
any string from the user, use
std::getline() :
1 2 3
string name;
cout << "Enter your name: " ;
getline( cin, name );
To get
anything else , make sure you get rid of the trailing newline:
1 2 3 4
int age;
cout << "Enter your age: " ;
cin >> age;
cin.ignore( numeric_limits<streamsize>::max(), '\n' );
You can make that simpler with a function:
1 2 3 4 5 6 7
template <typename T>
std::istream& inputline( std::istream& ins, T& value )
{
ins >> value;
ins.ignore( std::numeric_limits <std::streamsize> ::max(), '\n' );
return ins;
}
Now you can use it all easily:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
int main()
{
string name;
cout << "Enter your name: " ;
getline( cin, name );
int age;
cout << "Enter your age: " ;
inputline( cin, age );
string filename;
cout << "Enter a filename: " ;
getline( cin, filename );
if (filename.find( ".txt" ) = filename.npos)
filename += ".txt" ;
ofstream output( filename );
...
Hope this helps.
Topic archived. No new replies allowed.