Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read into std::string using scanf

Tags:

c++

c

string

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!

like image 349
Vlad Tarniceru Avatar asked Nov 23 '13 18:11

Vlad Tarniceru


People also ask

How do I scanf a string in C++?

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.

How do I read a string in scanf?

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.).

Can we use scanf () to read string with blank spaces?

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.

Can you use std :: string in C?

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.


2 Answers

this can work

char tmp[101]; scanf("%100s", tmp); string a = tmp; 
like image 155
Patato Avatar answered Sep 19 '22 15:09

Patato


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.

like image 38
Dietmar Kühl Avatar answered Sep 17 '22 15:09

Dietmar Kühl