0
Please fix this problem in my code !
#include <iostream> #include <fstream> #include <string> using namespace std; int main (){ int x = 0; string Text; ofstream myfile ("input.txt"); cout << "inter what is in your mind:" << endl; while (x == 0){ cin >> Text; myfile << Text; } myfile.close(); } What the code do ? it save the text that you write in file called input.txt What is the problem ? the problem is .... it just save the first word in the text for example : i wrote (Hello world i love potato) .. it save only (hello) in input. txt !!! Please help me
10 RĂ©ponses
+ 2
std::cin only takes any string until it encounters a space, therefore, u only got âhelloâ in ur txt file. here is a way to take a whole sentence as input (the working version of ur code) :
std::string text;
std::ofstream ofs(âa_file.txtâ);
std::getline(std::cin, text);
ofs << text;
ofs.close(); Mohammad Alshareef
0
Flash
Please ... are you sure that cin that take the text until space ??
This very important to me !
0
std::string a, b;
std::cin >> a >>b;
std::cin.ignore();
std::cout << a << std::endl << b;
//input: joe olson(+hit enter)
//output: joe
olson
btw, instead of asking me if iâm certain or not why donât u try out!?
if u understand the above code, then u shouldât be asking this. Mohammad Alshareef donât let someoneâs sololearn level to fool u!! thanks.
0
Flash
but this work !
do
{
cin>>data;
MyFile<<data<<" ";
}while(data!="exit");
MyFile.close();
}
0
Mohammad Alshareef would u mind writing the whole code, instead of writing some abstracts?
0
#include <fstream>
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
string data;
ofstream MyFile;
MyFile.open("nodpad.txt");
cout<<"write What in your mind : "<<endl;
do
{
cin>>data;
MyFile<<data<<" ";
}while(data!="exit");
MyFile.close();
}
0
nice,!
//input: i love exit
still cin only takes string untill space, here, it may seem u r taking the input as a whole sentence, but in reality u r providing input 3 times.
just put this:
cin>data;
cout>â???â
myfile<< data << â â
u will see ??? 3 times
since itâs loop input sentence was in the memory therefore, cin could access the next string after â â.
nonetheless, u need to put additional â â and u r gonna get âexitâ in ur output txt file as well. which i donât think uâd want. but if u still think iâm wrong try this:
std::string name;
std::cin >> name;
std::cout << name;
//in: max wild
//out: max
tell me why not max wild is printed? Mohammad Alshareef
0
Flash
you used cout not the stream name ... i just need to print the text in file not in the screen
0
Mohammad Alshareef that cout was not gonna print ur data on the console, the purpose was to illustrate how many times cin was used. anyway, just a suggestion, as a programmer u should understad why ur code works and vice versa. and if u did then u woudnât be asking those questions. all the best.
0
Flash
Thanks you for every thing ..You helped me alot ...