As the title said, I'm curious if there is a way to read a C++ string with scanf.
I know that I can read each char and insert it in the deserved string, but I'd want something like:
string a; scanf("%SOMETHING", &a);
gets()
also doesn't work.
Thanks in advance!
Just use scanf("%s", stringName); or cin >> stringName; tip: If you want to store the length of the string while you scan the string, use this : scanf("%s %n", stringName, &stringLength); stringName is a character array/string and strigLength is an integer. Hope this helps.
You can use the scanf() function to read a string. The scanf() function reads the sequence of characters until it encounters whitespace (space, newline, tab, etc.).
1) Read string with spaces by using "%[^\n]" format specifier. The format specifier "%[^\n]" tells to the compiler that read the characters until "\n" is not found. See the output, now program is able to read complete string with white space.
The std::string class manages the underlying storage for you, storing your strings in a contiguous manner. You can get access to this underlying buffer using the c_str() member function, which will return a pointer to null-terminated char array. This allows std::string to interoperate with C-string APIs.
this can work
char tmp[101]; scanf("%100s", tmp); string a = tmp;
There is no situation under which gets()
is to be used! It is always wrong to use gets()
and it is removed from C11 and being removed from C++14.
scanf()
doens't support any C++ classes. However, you can store the result from scanf()
into a std::string
:
Editor's note: The following code is wrong, as explained in the comments. See the answers by Patato, tom, and Daniel Trugman for correct approaches.
std::string str(100, ' '); if (1 == scanf("%*s", &str[0], str.size())) { // ... }
I'm not entirely sure about the way to specify that buffer length in scanf()
and in which order the parameters go (there is a chance that the parameters &str[0]
and str.size()
need to be reversed and I may be missing a .
in the format string). Note that the resulting std::string
will contain a terminating null character and it won't have changed its size.
Of course, I would just use if (std::cin >> str) { ... }
but that's a different question.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With