我目前正在使用 Visual Studio Community 2017。通过查看项目属性中的 C++ 语言标准,它们仅提供 C++14 和 C++17。由于我的代码是使用 C++11 编译器完成的先前分配的代码,因此我无法使用诸如 stoi 之类的函数运行我的代码。我的问题是,是否有办法将 C++11 添加到 C++ 的语言标准中?
我正在为 GUI 创建一个 DLL,我的初始化是:
#include <string>
#include "stdafx.h"
using namespace std;
在这里,我正在创建一个分数类,主要错误在 ifstream 中:
istream& operator>>(istream& in, Fraction& f) {
string number;
in >> number; //read the number
size_t delimiter = number.find("/"); //find the delimiter in the string "/"
if (delimiter != string::npos) { //if delimiter is not empty
int n = stoi(number.substr(0, delimiter)); //set numerator from string to integer before the "/"
int d = stoi(number.substr(delimiter + 1)); //set denominator from string to integer after the "/"
if (d == 0) { //if denominator is 0
throw FractionException("Illegal denominator, cannot divide by zero."); //illegal argument throw
}
else if (n == 0 && d != 0) { //numerator is 0, then set values as zero fraction
f.numVal = 0;
f.denVal = 1;
}
else { //set the values into the fraction and normalize and reduce fraction to minimum
f.numVal = n;
f.denVal = d;
f.normalizeAndReduce(f.numVal, f.denVal);
}
}
else { //else if there is no delimiter it would be a single integer
f.numVal = stoi(number);
f.denVal = 1;
}
return in;
}
我收到以下错误:
C2679: binary '>>': no operator found which takes a right-hand operator of type 'std::string"
C3861: 'stoi' identifier not found
这种方法在 Eclipse 中运行良好,不确定我做错了什么。
原文由 user3344484 发布,翻译遵循 CC BY-SA 4.0 许可协议
Visual C++ 2017 编译器与 C++11/C++14 兼容,但有一些特定例外:
编译器不提供特定的 C++11 模式,默认为 C++14,但该标准完全包含 C++11。 C++17 支持正在进行中,需要您使用 /std:c++17 或
/std::c++latest
开关。std::stoi
要求您包含适当的标头,特别是<string>>
您忘记包含该标头 - 或者 - 您没有处理namespace
分辨率(明确作为std::
或通过using namespace std;
)更新: 有关 Visual C++ 一致性的最新信息,请参阅 Microsoft Docs 。
现在您已经发布了代码,我发现问题与支持的标准 _无关_。您的问题是您不知道预编译标头如何工作的秘密。
改变:
至:
- 或 - 将
#include <string>
stdafx.h
中。请参阅 创建预编译的头文件