阅读C ++字符串scanf函数 [英] Read C++ string with scanf
问题描述
正如标题所说,我很好奇,如果有读取一个C ++字符串scanf函数的方式。
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);
获得()
也不起作用。
在此先感谢!
推荐答案
有没有的情况下获得()
是要使用!它的总是错误使用获得()
,它是由C11删除,并且从C ++ 14被删除。
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()的
好好尝试一下支持任何C ++类。但是,您可以scanf()的存储从结果成
的std ::字符串
:
scanf()
doens't support any C++ classes. However, you can store the result from scanf()
into a std::string
:
std::string str(100, ' ');
if (1 == scanf("%*s", &str[0], str.size())) {
// ...
}
我不能完全肯定指定在缓冲区lenght scanf函数的方式()
及顺序的参数去(有机会的参数&放大器;海峡[0]
和 str.size()
需要予以转回,我可能会丢失一个。
格式字符串)。请注意,生成的std ::字符串
将包含终止空字符,它不会改变它的大小。
I'm not entirely sure about the way to specify that buffer lenght 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.
当然,我只想用如果(给std :: cin>> STR){...}
但是这是一个不同的问题。
Of course, I would just use if (std::cin >> str) { ... }
but that's a different question.
这篇关于阅读C ++字符串scanf函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!