问题描述
我试过大部分的字符串和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);
)不起作用(并且不能通过给出不同的格式说明符)!
%s
格式说明符一起使用的b scanf()
需要相应的 char *
指针引用原始 char []
数组以接收参数列表中读取的数据。在你的例子中传递的 std :: string
指针不提供自动转换到引用 std :: string
实例内部管理 char []
缓冲区。
您可以尝试使用,但我不会真的推荐,除非你很确定你在做什么。 p>
,最好使用 std :: cin
和
std :: istream& operator>>(std :: istream& const std :: string&)
改为:
code> std :: cout<< Put in string value:<< std :: endl;
std :: string input;
std :: cin>>输入;
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 c++ you should better use std::cin
andstd::istream& operator>>(std::istream&, const std::string&)
instead:
std::cout << "Put in string value:" << std::endl;
std::string input;
std::cin >> input;
这篇关于如何使用scanf用C ++扫描字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!