To satisfy a curious mind. But again... THIS IS TERRIBLE:
1 2 3 4 5
std::string foo;
foo.resize(30); // resize foo to be 30 characters.
scanf("%s", &foo[0] ); // read in the string data (see notes below)
foo.resize( strlen( foo[0].c_str() ) ); // "fix" the length of the string to match what was input
Notes:
- This will only work reliably if the string data is contiguous... which I believe is only guaranteed in C++11.
- Using %s with scanf is bad. If the user inputs a string that is longer than 29 characters long, this code will explode.
- Never ever ever do this
- Just use iostream. It's safer and easier.
The problem with that is the hard-coded buffer size in the format string; even if the size of the buffer is a constant known at compile time, it won't pass a code review because of the maintenance hazard.
Canonical C code to read a string into a compile-time sized buffer looks like this. It is not a pretty sight for anyone; a sight that a C++ newbie shouldn't be exposed to.
1 2 3 4 5 6 7 8 9 10 11
#include <stdio.h>
int main()
{
enum { BUFSZ = 30 };
char name[BUFSZ] ;
char format[16] ;
sprintf( format, "%%%ds", BUFSZ-1 ) ;
scanf( format, name ) ;
}