如何使用scanf用C ++扫描字符串 [英] How to scan a string using scanf with C++

查看:140
本文介绍了如何使用scanf用C ++扫描字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试过大部分的字符串和char格式类型,他们不工作,我没有想法为什么。这是我的代码:

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

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

//在这里插入代码...
string string2;
string string;

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


解决方案

scanf(%s,& string); )不起作用(并且不能通过给出不同的格式说明符)!

$ b $与%s 格式说明符一起使用的b

scanf()需要相应的 char * 指针引用原始 char [] 数组以接收参数列表中读取的数据。在你的例子中传递的 std :: string 指针不提供自动转换到引用 std :: string 实例内部管理 char [] 缓冲区。



您可以尝试使用 & string.front() ,但我不会真的推荐,除非你很确定你在做什么。 p>

c ++ ,最好使用 std :: cin

std :: istream& operator>>(std :: istream& const std :: string&)
改为:

 code> std :: cout<< Put in string value:<< std :: endl; 
std :: string input;
std :: cin>>输入;

xcode 与您的问题不相关!)


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);
}

解决方案

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

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

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

For you should better use std::cin and
std::istream& operator>>(std::istream&, const std::string&) instead:

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

( isn't relevant for your question BTW!)

这篇关于如何使用scanf用C ++扫描字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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