如何在 C++ 中使用 scanf 扫描字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21716357/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 23:47:22  来源:igfitidea点击:

How to scan a string using scanf with C++

c++

提问by user3097544

I have tried most of the string and char format types and they are not working and I have no Idea why. Here is my code :

我已经尝试了大多数字符串和字符格式类型,但它们不起作用,我不知道为什么。这是我的代码:

#include <iostream>
#include <stdio.h>

using namespace std;
int main(int argc, const char * argv[])
{

    // insert code here...
    string string2;
    string string;

    cout << "Hello, World!\n";
    printf("Hi my name is Josh %s\n",string2);
    scanf("%s",&string);
    printf("hi %s",string);
}

回答by π?ντα ?ε?

What you're showing (scanf("%s",&string);) doesn't work (and never could, by e.g. giving different format specifiers)!

您显示的 ( scanf("%s",&string);) 不起作用(并且永远不会,例如通过提供不同的格式说明符)!

scanf()used with the %sformat specifier requires a corresponding char*pointer referencing a raw char[]array to receive the read data in the parameter list. The std::stringpointer you're passing in your example, doesn't provide automatic casting to the referred std::stringinstances internally managed char[]buffer that way though.

scanf()%s格式说明符一起使用需要一个char*引用原始char[]数组的相应指针来接收参数列表中的读取数据。std::string您在示例中传递的指针并没有以这种方式提供对std::string内部管理char[]缓冲区的引用实例的自动转换。

You could try to use &string.front()instead, but I wouldn't really recommend that, unless you're very sure what you're doing.

您可以尝试&string.front()改用,但我真的不建议这样做,除非您非常确定自己在做什么。

For c++you should better use std::cinand
std::istream& operator>>(std::istream&, const std::string&)instead:

对于C++,你应该更好地使用std::cin
std::istream& operator>>(std::istream&, const std::string&)而不是:

std::cout << "Put in string value:" << std::endl;
std::string input;
std::cin >> input;

(xcodeisn't relevant for your question BTW!)

(顺便说一句,xcode与您的问题无关!)

回答by Johnsyweb

You shouldn't mix std::coutwith ::printf. Prefer to use the C++ Standard IO libraryover C functions from stdio.

你不应该std::cout::printf. 更喜欢使用C++ 标准 IO 库而不是来自stdio.

Your code should look a little like this:

您的代码应该如下所示:

#include <iostream>

int main()
{
    std::string string2;
    std::string other_string;

    std::cout << "Hello, World!\n";
    std::cout << "Hi my name is Josh " <<  string2 << '\n';
    std::cin >> other_string;
    std::cout << "hi " << other_string;
}