使用scanf读入std :: string [英] Read into std::string using scanf

查看:69
本文介绍了使用scanf读入std :: string的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如标题所述,我很好奇是否可以通过scanf读取C ++字符串.

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()也不起作用.

提前谢谢!

推荐答案

在任何情况下都不会使用 gets()总是使用 gets()是错误的,它已从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 :: string :

scanf() doens't support any C++ classes. However, you can store the result from scanf() into a std::string:

编者注:如注释中所述,以下代码是错误的.查看 Patato Daniel Trugman 了解正确的方法.

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())) {
    // ...
}

我不确定在 scanf()中指定缓冲区长度的方式以及参数的顺序(参数& str [0] str.size()需要颠倒,我可能在格式字符串中缺少..请注意,生成的 std :: string 将包含一个终止的空字符,并且不会更改其大小.

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.

当然,我只会使用 if(std :: cin>> str){...} ,但这是一个不同的问题.

Of course, I would just use if (std::cin >> str) { ... } but that's a different question.

这篇关于使用scanf读入std :: string的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆