我是一名计算机科学专业的学生,现在正在上C++课。
我正在使用VSCode和g++作为编译器在Ubuntu上进行开发。
我从上次作业中扣除了积分,因为我忘记了包含字符串库,因此评分器出现了编译错误。
但是,在我的机器上,尽管不包括字符串库,但它仍然可以编译并运行而没有问题或警告。
好像g++捕获了这个错误,并在没有告诉我的情况下将其包括在内?有没有一种方法可以强制g++指示我忘记了字符串库?
这是我遇到此问题的代码:
#include <iostream>
using namespace std;
int main()
{
string output = "";
char inputChar;
// ask for input while the inputChar is not '0'
do
{
cout << "Enter a character: ";
cin.get(inputChar); // get input char from user
cin.ignore(100, '\n'); // ignore the newline character
switch( tolower(inputChar) ) // inputChar lowercase for simplified switch statement
{
// if inputChar is a vowel, capitalize and append to output string
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
output += toupper(inputChar);
break;
// if char is 0, exit switch without doing anything
case '0':
break;
// all other characters are appended to string in lowercase
default:
output += tolower(inputChar);
break;
}
} while (inputChar != '0');
// print full output string and exit
cout << "Your string: " << output << endl;
return 0;
}
最佳答案
#include仅仅是对所包含文件内容的字面剪切和粘贴(扩展了宏,并插入了文件/行标记,以便可以跟踪源)。
当包含iostream时,如果它在内部包含字符串,则表示您是在传递时包含字符串。这被认为是不好的,因为无法保证标准库头文件将包含其他头文件,因此您的代码不可移植,并且对所使用的标准库版本的依赖性很小。
如果您在代码中添加一个字符串包含,由于预处理程序可以防止重复的头文件包含,因此它将被彻底抑制,以至于在输出中都不会包含该偶数存在的证据。编译器无法处理任何内容,并且如果没有误报,就无法可靠地提供您想要的警告。
例如:假设我们有一个带有主文件的.cpp文件,以及一个名为a.hpp的 header :
header “a.hpp”:
#pragma once
namespace A {
void a_function() { }
}
header “b.hpp”
#pragma once
#include "a.hpp"
namespace B {
void b_function() { }
}
现在main.cpp看起来像这样:
#include "b.hpp" // only include b...
int main() { A::a_function(); } // ... but use something in a.hpp
可以编译但没有警告。预处理后的输出如下所示:
# 1 "main.cpp"
# 1 "<built-in>"
# 1 "<command-line>"
# 1 "/usr/include/stdc-predef.h" 1 3 4
# 1 "<command-line>" 2
# 1 "main.cpp"
# 1 "b.hpp" 1
# 1 "a.hpp" 1
namespace A {
void a_function() { }
}
# 3 "b.hpp" 2
namespace B {
void b_function() { }
}
# 2 "main.cpp" 2
int main() { }
看起来很合理,我们可以看到a被B包括在内,应该发出错误,对吗?
让我们修复它,然后重试:
#include "b.hpp"
#include "a.hpp"
int main() { }
再次预处理:
# 1 "main.cpp"
# 1 "<built-in>"
# 1 "<command-line>"
# 1 "/usr/include/stdc-predef.h" 1 3 4
# 1 "<command-line>" 2
# 1 "main.cpp"
# 1 "b.hpp" 1
# 1 "a.hpp" 1
namespace A {
void a_function() { }
}
# 3 "b.hpp" 2
namespace B {
void b_function() { }
}
# 2 "main.cpp" 2
int main() { }
100%与以前相同。 我们已解决了该问题,但预处理后的输出中没有任何指示。
除非预处理器提供了更多信息,否则编译器中的任何更改都无法满足您的请求。
关于c++ - 强制g++指示何时不包含库,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54507858/