使用 scanf 读取 C++ 字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20165954/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Read C++ string with scanf
提问by Vlad Tarniceru
As the title said, I'm curious if there is a way to read a C++ string with scanf.
正如标题所说,我很好奇是否有办法使用 scanf 读取 C++ 字符串。
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.
gets()
也不起作用。
Thanks in advance!
提前致谢!
采纳答案by Dietmar Kühl
There is no situation under which gets()
is to be used! It is alwayswrong to use gets()
and it is removed from C11 and being removed from C++14.
没有什么情况下gets()
可以使用!它总是错误的使用gets()
,它是由C11删除,并且从C ++ 14中移除。
scanf()
doens't support any C++ classes. However, you can store the result from scanf()
into a std::string
:
scanf()
不支持任何 C++ 类。但是,您可以将结果存储scanf()
到 a 中std::string
:
Editor's note: The following code is wrong, as explained in the comments. See the answers by Patatoand tomfor 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.
我不完全确定指定缓冲区长度的方式scanf()
以及参数的顺序(参数&str[0]
和参数有可能str.size()
需要反转,我可能会.
在格式字符串中丢失 a )。请注意,结果std::string
将包含一个终止空字符,并且不会更改其大小。
Of course, I would just use if (std::cin >> str) { ... }
but that's a different question.
当然,我只会使用,if (std::cin >> str) { ... }
但这是一个不同的问题。
回答by Patato
this can work
这可以工作
char tmp[101];
scanf("%100s", tmp);
string a= tmp;
回答by Srijan Shashwat
The below snippet works
下面的片段有效
string s(100, 'int n=15; // you are going to scan no more than n symbols
std::string str(n+1); //you can't scan more than string contains minus 1
scanf("%s",str.begin()); // scanf only changes content of string like it's array
str=str.c_str() //make string normal, you'll have lots of problems without this string
');
scanf("%s", s.c_str());
回答by sudo-gera
std::string str(100, ' ');
scanf("%100s", &str[0]);
回答by tom
You can construct an std::string of an appropriate size and read into its underlying character storage:
您可以构造一个适当大小的 std::string 并读入其底层字符存储:
##代码##(There is no off-by-one error with the sizes, because since C++11 it is guaranteed that the character data of std::string is followed by a null terminator.)
(大小没有逐一错误,因为从 C++11 开始,保证 std::string 的字符数据后跟空终止符。)