strings in c++

i have a
string something

how should i scanf it?

scanf("%s",&something); does not work ofc so how should i do it?
Don't mix C++ strings with C i/o. They generally don't play nice together.

So basically.. don't use scanf. Use iostream (cin):

1
2
3
4
5
6
7
std::string foo;

// if you want to stop at whitespace:
cin >> foo;

// or if you want to get the entire line
getline(cin, foo);

Last edited on
yes i know that but i remember that there is a trick for scanf too
Don't use tricks. Use stable code that works.

Any hack that you come up with to make a std::string work with scanf will be error prone at best or have undefined behavior at worst.


EDIT: not to mention %s with scanf is a bad idea anyway (even in C) because there is no way to protect against buffer overflow.
Last edited on
just for testing and curiosity use i am not making programs with that :P
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.
Last edited on
yeah thats that :D ty
closed account (o1vk4iN6)
Probably shouldn't have posted that, looks like he's using it anyways, lol.
closed account (S6k9GNh0)
(obligatory mention that there is buffer overflow protection for %s in scanf as you can limit number of characters read in with width specifier)
Last edited on
@computerquip:

So would that be scanf("%29s", &foo[0]); then? My printf/scanf codes are rusty.
closed account (S6k9GNh0)
Pft, I dunno lol. Just saying that it's possible. To say something is impossible means that it can't be done. That's a radical statement. :D
Last edited on
> So would that be scanf("%29s", &foo[0]);

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 ) ;
}
Topic archived. No new replies allowed.