当诸如“iostream”之类的库已经提供解决方案时,您是否包含“字符串”标题?
示例:如果已包含iostream库,是否包含字符串库?哪种是正确的专业方法?
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ifstream fin;
fin.open("input.txt");
string data;
fin >> data;
cout << data << endl; // Works with <iostream>, and without <string>
fin.close();
return 0;
}
示例2:如果另一个库提供功能,则使用字符串库,即使程序编译没有字符串?
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main() {
ifstream fin;
fin.open("input.txt");
string data;
fin >> data;
cout << data << endl; // Even though <iostream> allowed program to compile, we include the <string> library.
fin.close();
return 0;
}
从我的CSC 101类编程作业中获得了分数,因为即使程序工作,老师说当使用字符串数据类型时我需要包含字符串库。即使从技术上讲,没有它可能也没问题。这就是问题所在。
你的老师是对的。
你的程序没有偶然的<string>
工作。您在该平台上的那个版本的标准库实现,在那一天,在那一天,通过<iostream>
传递包含您需要的内容。标准库只是代码,就像你的代码一样,你的特定实现恰好包含在<iostream>
中的#include <string>
。它可能被埋在许多其他#include
s后面,但最终到达那里。但这实际上是纯粹的机会,并不意味着这是语言保证的东西,或者即使在实践中也必须始终如此。
您应该始终编写标准代码。
如果你正在使用features from <string>
,请加入<string>
。
就在今天,我正在尝试使用新的工具链构建我的大项目,并发现了一些我不小心依赖传递包含的地方,并且因为新的标准库实现具有略微不同的标题排列而打破了构建。我尽职尽责地添加了缺少的#include
s,现在世界是一个更好的地方。