Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

indefinite string entry

Status
Not open for further replies.

rockbold

Technical User
Dec 20, 2004
11
US
Hello guys

I am new at c++
Please let me know the easiest way to enter
a string when you dont know how long your string
is going to be. Thanks.

rockbold
 
It depends on how the string is being entered. Assuming that you are using console input with cin, then the solution is to use the C++ string class. It grows automatically to the size of the input.

If you are using some sort of Windows based input, then you should probably provide more information on what you are doing.
 
Well, there's a couple of ways you can accomplish this.

First, create an array of a large size that you know will not be exceeded.

Code:
char largearray[100000];

Another approach, you can use a character pointer. The only problem with this is that if the string is REALLY large, you might overwrite memory that is being utilized by other processes/variables.

Code:
char *myString;
myString = "This is a very long sentence that is using a character pointer.";

Lastly, you can use the standard template library and use the string class. Depending on your system, I believe the declaration should be as follows...

Code:
#include <string>

...

using namespace std;

...

string myString;
myString = "This is another long string.  Blagh, blagh, blagh!";

The nice thing about the string class is that -- I believe -- the string is dynamically allocated, so you don't have to worry about allocation or writing over memory allocated in other programs. I'd suggest using this method to accomplish your problem.
 
Another approach, you can use a character pointer.
I sure hope you're not talking about doing something like this!
Code:
char* str;
cin >> str;
I'm assuming he wants to read the string from a file or keyboard.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top