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]
Undetermined string length
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
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.
Use the functional form of std::getline to read into std::strings.
std::string mystring;std::getline( std::cin, mystring );
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement