【问题标题】:Why I can't use string? [duplicate]为什么我不能使用字符串? [复制]
【发布时间】:2016-12-30 10:54:27
【问题描述】:

我有以下代码

#include <iostream>
#include <string>

main(){
    std::cout << "What's Your Name? ";
    string x = "";
    std::cin >> x;
    std::cout << std::endl << "Nice to meet you " << x << "!" << std::endl;
}

我得到了这个错误

Running /home/ubuntu/workspace/client.cpp
/home/ubuntu/workspace/client.cpp: In function ‘int main()’:
/home/ubuntu/workspace/client.cpp:6:5: error: ‘string’ was not declared in this scope
     string x = "";
     ^
/home/ubuntu/workspace/client.cpp:6:5: note: suggested alternative:
In file included from /usr/include/c++/4.8/iosfwd:39:0,
                 from /usr/include/c++/4.8/ios:38,
                 from /usr/include/c++/4.8/ostream:38,
                 from /usr/include/c++/4.8/iostream:39,
                 from /home/ubuntu/workspace/client.cpp:1:
/usr/include/c++/4.8/bits/stringfwd.h:62:33: note:   ‘std::string’
   typedef basic_string<char>    string;   
                                 ^
/home/ubuntu/workspace/client.cpp:6:12: error: expected ‘;’ before ‘x’
     string x = "";
            ^
/home/ubuntu/workspace/client.cpp:7:17: error: ‘x’ was not declared in this scope
     std::cin >> x;
                 ^

为什么我不能使用字符串?我正在使用 Cloud9 运行它,并且对 C++ 比较陌生。如何将cin 的输入转换为字符串x

【问题讨论】:

  • std::string 不是string
  • 旁注:它是int main(),基本的main()ill-formed
  • 对于像这样的小型项目,您可以在包含后立即执行using namespace std;
  • 看起来你正在学习一个古老的教程,需要从这个千年升级到一些东西。
  • 答案在错误消息中:“注意:建议的替代方案:...'std::string'”。

标签: c++ string cin


【解决方案1】:

您必须指定命名空间:将string 更改为std::string

【讨论】:

  • 补充:那是因为string本身在C++原生中是不存在的,只能使用,因为它是在&lt;string&gt;中定义的。因为它位于std 命名空间中,所以您必须编写std::string 而不是string。您确实可以创建 typedef (typedef string std::string) 或使用定义:#define STRING std::string
  • ...或者你可以使用using std::string
  • 我从未在 C++ 中看到过,但你知道的越多……谢谢
  • 别忘了@bjskistad,你也应该写int main(),而不仅仅是main,它被认为是糟糕的代码。
猜你喜欢
  • 1970-01-01
  • 2021-10-27
  • 1970-01-01
  • 2021-05-09
  • 2018-10-18
  • 2017-09-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多