string b;
ofstream outputFile;
cout << "What do you want to call the new output file " << endl;
cin >> b;
outputFile.open(b, ofstream::out);
string sent1;
cout << "Enter a sentence: ";
cin >> sent1;
outputFile << sent1 << endl;
if (outputFile.fail()){
cerr << "Opening file..." << b << " failed." << endl;
cerr << "Program Exit" << endl;
exit(1);
}
outputFile.close();
For some reason when i write the text i want to appear in the text it only produces the first word i write for example Hi how are you? // I'll open the file and then only Hi will be inside of it. How do i fix that
It's because cin >> sent1; only inputs one word into sent1.
If you want it to grab a whole line of text, use getline(cin, sent1);.
EDIT: Oh, but be careful of mixing cin >> something; and getline(cin, somethingelse); together in your code.
If you do cin >> something;, it'll leave behind a newline character in the input stream, and that'll cause getline to gobble that up instead of stopping for more input.
The best solution to that would be to do something like
1 2 3 4
cin >> something;
cin.ignore(numeric_limits<streamsize>::max(), '\n'); // Get rid of that newline (and whatever else)
// ...
getline(cin, somethingelse); // Now this should work
For most purposes, it's probably okay to just do something like cin.ignore(9999, '\n'); or cin.ignore(80, '\n'); or even just cin.ignore(); after you use cin >> something;.
The only time that becomes a problem is if you decide you wanted to enter more than 9999 (or 80, or 1) characters after the thing you're "supposed" to input. (Then getline will eat whatever's left instead of waiting for you to enter something)
Basically, the #include <limits> is only so you can use numeric_limits<streamsize>::max() (which basically tells cin.ignore to eat as many characters as possible until it reaches a newline character).