I created a program that accepts input from the keyboard and stores it in a string. Then it outputs the string in a file. This works, and is as follows:
Code:
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
int main()
{
string sentence;
ofstream file;
char filename[100];
cout << "Enter text to be written to file: ";
getline(cin, sentence);
cout << endl;
cout << "The text will be written to the current directory (contains the .cpp file)." << endl;
cout << "The file will be called Output.txt" << endl;
file.open("Output.txt", ios::out);
file << sentence;
file.close();
cout << endl;
cin.get();
cout << endl;
return 0;
}
The problem:
In unix, I have to redirect the stdin to a file (a.out < file.txt). So, I want this to read all the contents of "file.txt" into the string. However, only the first line of the file is being read into string. I think it probably has something to do with getline, but i'm not sure how to fix it. I thought getline is suppose to include all whitespace, but maybe it has something to do with unix (\n or endl?).
By the way, I'm trying to use a string instead of a char.
This is an example of the file:
Code:
This is sample text that needs
to be read correctly. More sample
text is as follows.
Only the first line reads into the string.
Thanks.