Monday, May 24, 2010

Is it possible to declare string variable in a c++ console application.?

Hi there its a pretty simple question, I am self teaching myself C++ and working on a simple input/output application, I have gotten it working for the most part, but the output is always a number, I learned this was because I declared it as int (interger)





Well I know float is a number with decimals, and I know char grabs the first letter, but how do I grab the whole word. In VB it was just Dim X as String. Does C++ have a statement like this or do I need to start coding a class that will convert the number to string data taking it a letter at a time.

Is it possible to declare string variable in a c++ console application.?
Similar to the person who answered before me,


a char array is the c equivalent of a string.


But, you have to have a maximum size for it.





char text[100];





to get this from input, you can call


cin %26gt;%26gt; text;


but, if the input is longer than the array size, there will be overflow, possibly writing onto some other information. BAD.





Your best bet would be to use the standard string.


Need to #include %26lt;string%26gt; or #include %26lt;string.h%26gt;, then use





string str;





cin %26gt;%26gt; str;





You will get the whole string then. String has a lot of helpful functions, have a look at some source or h files if you can.


Perhaps, the most important one is to get a char array from the string to use in fuctions that need a char * (which is a char array).





str.c_str();
Reply:You can declare a C style string with:





char whatever[30]; // 30 character string space





or a C++ 'string', first by includding the string header:


#include %26lt;string%26gt;





and in your code,declaring them





string * whatever = new string(); // size not required





For both types, there are lots of functions and operators that let you manipulate them.

flower pots

No comments:

Post a Comment