Sunday, July 12, 2009

C++ Needs help with my code?

My current problem is i wanted the user to type I am great, and save it under a txt file. but somehow it only display "I"





#include %26lt;iostream%26gt;


#include %26lt;fstream%26gt;


#include %26lt;string%26gt;


using namespace std;








int main()


{


void Enter();


Enter();


return 0;


}





void Enter()


{


void Done();





ofstream fout;





string szLine ="";


string szWord = "";


string szName = "";


string szType ="";





//Starting//


cout%26lt;%26lt;"Please enter your name: "; cin%26gt;%26gt;szName;


cout%26lt;%26lt;endl%26lt;%26lt;endl;


cout%26lt;%26lt;"Please enter the follow sentence: I am Great."; cin%26gt;%26gt;szType;


cout%26lt;%26lt;endl%26lt;%26lt;endl;


fout.open("Stats.txt");


fout %26lt;%26lt; "Name: " %26lt;%26lt; szName %26lt;%26lt; endl;


fout %26lt;%26lt; "Typed: " %26lt;%26lt; szType %26lt;%26lt; endl;


fout.close();


Done();


}





void Done()


{


cout%26lt;%26lt;"Thanks check the text."%26lt;%26lt;endl;


}

C++ Needs help with my code?
You need to have a prototype for the functions inside the main(). It should be written before the main. To resolve it quickly, put the main function at the bottom part.





OR: edit the code





#include %26lt;iostream%26gt;


#include %26lt;fstream%26gt;


#include %26lt;string%26gt;


using namespace std;





void Done(); // prototype for function Done()


void Enter(); // prototype for function Enter()





int main()


{


void Enter();


Enter();


return 0;


}





then: use cin.getline(); instead of cin only
Reply:Very few people here knows how to code, so I recommend finding a good programmer's forum or IRC channel. Do a google search for "programmer's forum".
Reply:when you have a sub that's getting called in the main, you need to write its code before the main.
Reply:OK, here is your problem. cin implicitly parses your input according to spaces and a few other delimiters.





So when you cin to a string, you are getting only the first word of your string. "I am great" will only capture "I" on one cin.





In order to capture all text before the user hits enter, use this:





cout %26lt;%26lt; "Please enter the following sentence: I am Great";


getline(cin, szType);





EDIT: the delimiters I mentioned before are space, tab, and newline ( http://www.cplusplus.com/doc/tutorial/ba... )
Reply:don't have time right now, but here is a link that will teach you:


http://cprogramming.com/


No comments:

Post a Comment