完全是新手,我有一个关于代码中换行符的快速问题。所以我知道插入 using namespace std
是不好的做法,在编写我的程序时,我避免使用 cout
和 cin
而不添加 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/