Archived

This topic is now archived and is closed to further replies.

C++: Getting Input Gauranteed not to Overflow Buffer

This topic is 5047 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

How can I get input into a buffer from standard input that will be gauranteed not to overflow my allocated memory? What function can I use? Thanks

Share this post


Link to post
Share on other sites

do
{
// tell user thats to big
// re-ask for input
// take input
}while(strlen(userinput) <= MAX_ALLOCATED);

using strlen u can check length of a "string" assuming thats what your doing?
or just use strncpy(...) then u can define the number of characters to copy >.<

[edited by - DevLiquidKnight on February 22, 2004 2:05:35 AM]

Share this post


Link to post
Share on other sites
A line:


#include <iostream>
#include <string>

int main()
{
std::string str;
std::getline(std::cin, str);
}


All of standard input until it gets closed:


#include <iostream>
#include <iterator>
#include <string>

int main()
{
std::string str( std::istreambuf_iterator<char>(std::cin),
std::istreambuf_iterator<char>() );
}


C++ container classes like std::string and std::vector are intended to grow as needed.


“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 (C programming language co-inventor)


[edited by - Fruny on February 22, 2004 2:12:57 AM]

Share this post


Link to post
Share on other sites