2013-06-20 166 views
3

我收到此错误字符串未声明编译此代码时。编译代码时出错

#include <stdio.h> 
#include <stdlib.h> 


int main() 
{ 
string names; 
printf("What is your name?\n"); 
scanf("%s", &names); 

printf("Your name is %s", names); 
return 0; 
} 

有人可以告诉我为什么。非常感谢

+0

包含'string'标头。并像@taocp所说的那样添加'std'。 –

+0

另外,'printf'是一个C函数,它不知道流。使用'cin'和'cout'来代替旧的C函数。 – Wug

+0

你使用哪种编译器? – banuj

回答

8

你应该包括串标头:

#include <string> 

,并使用时,不要忘了命名空间std

std::string names; 

此外,不要在混合C和C++代码你。尝试使用std::cout而不是printf,cin/getline而不是scanf

+2

特别是,将'std :: string'对象(本例中的名称)作为参数传递给'printf'肯定不会按预期工作。 –

+0

@MatsPetersson这是我忽略的另一个重点。谢谢! – taocp

0

因为std :: string是在头文件字符串中定义的,而你没有包含它,并且因为它的完整名称是std :: string,而不是字符串。

3

您需要添加

#include <string> 

引用从C字符串++标准库和状态,你使用std与

using namespace std; 

here

2

如果您正在编写C++,那么标准字符串类被称为std::string,并且位于标头<string>中。但是,你通常不会想用printfscanf有了它,你会使用C++ I/O:

#include <iostream> 
#include <string> 

int main() 
{ 
    using namespace std; 
    string names; 
    cout << "What is your name?" << endl; 
    getline(cin, names); 
    cout << "Your name is " << names << endl; 
} 

如果(尽管问题标签),你在写C,那么就没有所谓的类型string。字符串由字符数组常规表示:

char names[SOME_LARGE_NUMBER]; 

但要注意的是,除非你非常小心,scanf可能使缓冲区溢出并导致运行时错误的所有方式。

0

您错过了包含printfscanf的定义的头文件。将#include <string.h>添加到代码中。

此外,我认为代码在最后没有return 0;行。