c++ - 如果我注释掉换行符,为什么 'string' 会成为不合格的变量

标签 c++ namespaces using

完全是新手,我有一个关于代码中换行符的快速问题。所以我知道插入 using namespace std 是不好的做法,在编写我的程序时,我避免使用 coutcin 而不添加 std:: 部分首先。但我认为由于我没有导入 namespace 库,所以我可以将其注释掉。但是当我这样做时,我的变量的 string 名称变得无法识别(它下面的红线)。当我允许再次导入 namespace 时,红线消失了。变量 string 是否仅在 namespace 库中可用?

#include "stdafx.h"
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <cmath>
//using namespace std;



// read and compare names
int main()
{
    std::cout << "Please enter two names \n";
    string first;
    string second;
    std:: cin >> first >> second; // read two strings
    if (first == second) std::cout << "that's the same name twice! \n";
    if (first < second) std::cout << first << " is alphabetically before " 
<< second << '\n';
    if (first > second) std::cout << first << " is alphabetically after " << 
second << '\n';

return 0;
}

最佳答案

如果您不包含 using namespace std 那么您需要说明

std::string first;
std::string second;

因为 string 也在 standard 命名空间中定义(以及 cout 等)。

是的,您是对的,string 仅在 standard 中定义。 string 是一个对象(不是原始类型),它允许您进行 if(first==second) 比较。否则,比较字符串的“正常”方法是使用 strcmp() 或类似方法。

关于c++ - 如果我注释掉换行符,为什么 'string' 会成为不合格的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52638073/

相关文章:

c++ - Visual Studio C++ 将 "junk"添加到我的程序中

JavaScript 命名空间建议

c# - 找不到命名空间!

javascript - js - 避免 namespace 冲突

python - 动态分配变量

php - 我想在mysql中使用php实现行级锁定

c# - .NET - 用单个 using 语句替换嵌套的 using 语句

c++ - 多次包含命名空间的链接器错误

c++ - clone_ptr 实现错误

c++ - 当退出时 C++ 中的库不是 "cleaned up"时会发生什么