Undetermined string length

Started by
2 comments, last by bioagentX 20 years, 3 months ago
Does anyone know of to read in a string of undetermined length in a console app in c++? I don't know how to go about it seeing as that all the examples of such things use strings of finite length. For example, here is my problem


int main()
{

char charArray[20];
//char array made for 20 chars


cout<<"Enter a string of undetermined length: ";

cin.getline(charArray, 20, '\n');
//read in the array


return 0;

}

As you can see from the above source, if the user enters in a string that has more than 20 characters, the program will output some undesired results. I am wondering if there is some small algorithm that can be used to get around this problem. I already considered using dynamic memory, but that would require determing the string's length beforehand, and then adjusting the array size. The problem with this option is that, if there isn't enough memory allocated for the string in the first place, an accurate string length cannot be gathered. If someone knows how to overcome this problem, please help. Thanks, --BioX [edited by - BioagentX on January 5, 2004 2:40:20 AM] [edited by - BioagentX on January 5, 2004 2:41:06 AM]
There are three types of people in this world, those who can count, and those who can't
Advertisement
use std::string instead of char [].

#include <iostream>#include <string>int main(){  std::string item;  std:: cout<<"Enter a string of undetermined length: ";  std::cin >> item;  std::cin.ignore ();  //eat the return  return 0; }
>> only reads up to the first whitespace character.
Use the functional form of std::getline to read into std::strings.

std::string mystring;std::getline( std::cin, mystring ); 

"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan
cool, thx a lot.
There are three types of people in this world, those who can count, and those who can't

This topic is closed to new replies.

Advertisement