| View previous topic :: View next topic |
| Author |
Message |
Engineer Expert Cheater
Reputation: 1
Joined: 25 Nov 2007 Posts: 170
|
Posted: Sun Aug 10, 2008 6:22 am Post subject: [c++] Problem writting to a txt... |
|
|
Hello, I'm making a file that writes to a txt file (just for testing), but it only writes the first word of the string
Here's the script:
| Code: | /* Text File Writer */
/* Includes */
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
/* Function */
int main( void ) {
string writethis;
ofstream write ("input.txt");
if (write.is_open()) {
std::cout << "Write down the output for 'input.txt', please.\n";
std::cin >> writethis;
write << writethis;
write.close();
std::cout << "Done. Press enter to close.";
}
else { cout << "Error: Unable to locate file.\n"; }
std::cin.sync();
std::cin.ignore();
return 0;
}
|
How can I fix this problem?
|
|
| Back to top |
|
 |
redhead Cheater
Reputation: 0
Joined: 21 Mar 2007 Posts: 47
|
Posted: Sun Aug 10, 2008 6:41 am Post subject: |
|
|
try std::cin.getline() instead of std::cin .
| Code: | /* Text File Writer */
/* Includes */
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
/* Function */
int main( void ) {
char writethis[256];
ofstream write ("input.txt");
if (write.is_open()) {
std::cout << "Write down the output for 'input.txt', please.\n";
std::cin.getline (writethis,256);
write << writethis;
write.close();
std::cout << "Done. Press enter to close.";
}
else { cout << "Error: Unable to locate file.\n"; }
std::cin.sync();
std::cin.ignore();
return 0;
} |
|
|
| Back to top |
|
 |
Engineer Expert Cheater
Reputation: 1
Joined: 25 Nov 2007 Posts: 170
|
Posted: Sun Aug 10, 2008 6:48 am Post subject: |
|
|
| redhead wrote: | try std::cin.getline() instead of std::cin .
| Code: | /* Text File Writer */
/* Includes */
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
/* Function */
int main( void ) {
char writethis[256];
ofstream write ("input.txt");
if (write.is_open()) {
std::cout << "Write down the output for 'input.txt', please.\n";
std::cin.getline (writethis,256);
write << writethis;
write.close();
std::cout << "Done. Press enter to close.";
}
else { cout << "Error: Unable to locate file.\n"; }
std::cin.sync();
std::cin.ignore();
return 0;
} |
|
Thanks, It worked.
|
|
| Back to top |
|
 |
Jani Grandmaster Cheater
Reputation: 2
Joined: 29 Dec 2006 Posts: 804
|
Posted: Sun Aug 10, 2008 7:58 am Post subject: |
|
|
If you want to get rid of that 256 character limit: | Code: | #include <string>
std::string s;
std::getline(std::cin, s);
file << s; |
|
|
| Back to top |
|
 |
|