i'm sure it has something to do with the "cin" or "getline" functions i've been trying to solve this problem with storing a string with spaces and save it to a text file but i can't seem to get it. an insertion error or infinite loop happens.
char title[ ]="";
string msg;
string temp;
char txt[ ] = ".txt";
string tempz;
ofstream myfile, myfile2;
system("cls");
cout %26lt;%26lt; "Title of message: ";
cin %26gt;%26gt; title;
tempz=title;
cout %26lt;%26lt; endl%26lt;%26lt;"Enter message: ";
getline(cin,msg);
temp = msg;
strcat(txt,title);
myfile.open (title);
myfile2.open("outbox.txt",ios::app);
myfile %26lt;%26lt;tempz %26lt;%26lt; endl %26lt;%26lt; temp %26lt;%26lt; endl %26lt;%26lt; endl;
myfile2 %26lt;%26lt; tempz %26lt;%26lt; endl %26lt;%26lt; temp %26lt;%26lt; endl %26lt;%26lt; endl;
myfile.close();
myfile2.close();
Whats wrong with my code? C++?
I can tell you at least one problem with your code. strcat(txt,title). Take a good look: http://www.cppreference.com/stdstring/st... or http://www.cplusplus.com/reference/clibr...
If you don't know how to work with C strings, don't randomly guess with functions. Either learn how C strings or don't use them at all.
Look at how strcat works. It's an append. so strcat (txt,title) is like txt + title, not title+txt. Your order is wrong. However, you have a bigger problem. You don't have enough of a buffer to do the concatenation.
If you were to do strcat(title,txt) (this would be the correct order), you would run into a problem. The C string title has enough space only for title. You can't fit txt into it. You should allocate a buffer big enough for both title and txt.
WHat's really confusing is that this is a perfect reason to use a *C++* string. Actually, your whole logic is a bit messy. You have a bunch of random C strings, C++ strings, and unnecessary assignments. Might want to clean up that code there.
Reply:You're not allocating any memory for title. You need to do something like:
char *title = new char[20];
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment