I have put this code in int main() and it worked fine but in a separate function is just runs straight thru non stop for users input ? I got this code from a already asked question .. just debugged it and it says theirs an error on line 4 "ofstream f;"
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
void makefile(){
ofstream f;
string filename;
cout << "Please enter a file name to write: ";
getline( cin, filename );
f.open( filename.c_str() );
f << "Hello world!\n";
f.close();
cout << "Success\n";
}
Chances are you have, somewhere else in your program, something like
cin >> x;
Right?
What no one teaches new programmers in C++ (and C) is that you should always read user input as a whole-line string, then convert that string to what you want.
Yes, I know that cin is an istream, with all kinds of nice, overloaded extraction functions, but you shouldn't use them. Use an istringstream for that.
The reason is fairly simple: The user will always press Enter at the end of every input!
I find useful functions to be... well, useful. Here's a full-fledged example to get started:
#include <iostream>
#include <sstream>
#include <string>
int get_an_integer( std::istream& ins )
{
// Get an entire line input from the user
std::string s;
std::getline( ins, s );
// Get rid of any trailing whitespace
s.erase( s.find_last_not_of( " \t\r\n\f\v" ) + 1 );
// Try to convert it to the object of our desire (an int)
std::istringstream ss( s );
int result;
ss >> result;
// Check for success or failure.
if (!ss.eof()) cin.setstate( std::ios::failbit );
// Return the (potentially invalid) result
return result;
}
int main()
{
usingnamespace std;
int age;
string name;
cout << "How old are you? ";
age = get_an_integer( cin );
cout << "What is your name? ";
getline( cin, name );
int main()
{
usingnamespace std;
int age;
string name;
cout << "How old are you? ";
while (true)
{
age = get_an_integer( cin );
if (!cin or (age < 0))
{
cin.clear();
cout << "Your age must be a whole number, like 24 or 7. How old are you? ";
}
elsebreak;
}
cout << "What is your name? ";
while (true)
{
getline( cin, name );
name.erase( name.find_last_not_of( " \t\n\r\f\v" ) + 1 );
if (name.empty())
{
cout << "You must have a name. What is it? ";
}
elsebreak;
}
if (age < 3)
cout << "Hey, " << name << ", you're a good reader!\n";
else
cout << name << ", " << age << " years old, earns 7 EP.\n";
And now you know the ugly truth. Input is difficult.