【问题标题】:Why would 'string' become an ineligible variable if I comment out Newline如果我注释掉换行符,为什么“字符串”会成为不合格的变量
【发布时间】:2018-10-04 02:18:46
【问题描述】:

完整的新手在这里,我有一个关于我的代码中的 newline 的快速问题。所以我知道插入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;
}

【问题讨论】:

    标签: c++ namespaces using


    【解决方案1】:

    如果你不包括using namespace std那么你需要说

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-03
      • 2020-01-28
      • 2017-11-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多