[英]How to use a string entered in a txt file as an if condition
一个function包含一个vector的function被包含在一个叫做Vector的class中。 我会通过txt文件中输入的字符串来确定主function使用哪个function。
class Vector
{
public: // private?
double x, y, z;
public:
Vector() {
x = 0;
y = 0;
z = 0;
}
Vector(int _x, int _y, int _z) {
x = _x;
y = _y;
z = _z;
}
Vector Add(Vector v) {
Vector output;
output.x = x + v.x;
output.y = y + v.y;
output.z = z + v.z;
return output;
}
double Dot(Vector v) {
double output;
output = (x * v.x) + (y * v.y) + (x * v.y);
return output;
}
};
这是主要的function,我想在txt文件中使用我要接收的字符串,但效果不佳。 此代码下方有一个详细示例。
int main()
{
FILE* fpInput;
FILE* fpOutput;
int vectorAx, vectorAy, vectorAz, vectorAdim;
int vectorBx, vectorBy, vectorBz, vectorBdim;
char VecFun[10];
fpInput = fopen("input.txt", "r");
fscanf(fpInput, "%d %d %d", &vectorAx, &vectorAy, &vectorAz);
fscanf(fpInput, "%d %d %d", &vectorBx, &vectorBy, &vectorBz);
fclose(fpInput);
fpInput = fopen("input.txt", "r");
fgets(VecFun, sizeof(VecFun), fpInput);
fclose(fpInput);
Vector vectorA(vectorAx, vectorAy, vectorAz);
Vector vectorB(vectorBx, vectorBy, vectorBz);
if (VecFun == "Add") {
Vector vectorO = vectorA.Add(vectorB);
fpOutput = fopen("output.txt", "w");
fprintf(fpOutput, "%.f %.f %.f", vectorO.x, vectorO.y, vectorO.z);
fclose(fpOutput);
}
else if (VecFun == "Dot") {
fpOutput = fopen("output.txt", "w");
fprintf(fpOutput, "%.f", vectorA.DotProduct(vectorB));
fclose(fpOutput);
}
else {
printf("Invalid input.. (%s)\n", VecFun);
}
return 0;
}
输入.txt :
Add
1 2 3
4 5 6
输出.txt :
5 7 9
输入.txt :
Dot
1 2 3
4 5 6
输出.txt :
32
但是,if 条件不起作用,所以我尝试使用以下方法进行调试:
printf("Invalid input.. (%s)\n", VecFun);
并找到了这个结果:
为什么会出现这些结果? 另外,如何修改 if 条件才能工作?
您不能使用==
运算符比较 C 风格的字符串是否相等。 在像if (VecFun == "Add")
这样的代码中, VecFun
变量( char
数组的名称)和"Add"
(字符串文字)都衰减为指向其第一个元素的指针; 并且,由于它们是位于不同memory 位置的不同项目,该测试将始终导致false
值。
在C中,您需要使用strcmp
function,如上面链接问题的答案所示。 但是,在C++ (C++14 起) 中,您可以使用s
后缀将文字指定为std::string
对象; 然后,像VecFun == "Add"s
这样的测试将按预期工作。 1个
这是一个简短的演示:
#include <iostream>
#include <string>
using namespace std::string_literals;
int main()
{
char test[10] = "Add";
// Wrong - comparing two different pointers ...
if (test == "Add") {
std::cout << "Raw comparison succeeded!\n";
}
else {
std::cout << "Raw comparison failed!\n";
}
// Plain "C" way, using the strcmp function ...
if (strcmp(test, "Add") == 0) {
std::cout << "strcmp comparison succeeded!\n";
}
else {
std::cout << "strcmp comparison failed!\n";
}
// C++ way, using std::string literals ...
if (test == "Add"s) {
std::cout << "std::string comparison succeeded!\n";
}
else {
std::cout << "std::string comparison failed!\n";
}
return 0;
}
1如果您的编译器不支持 C++14 标准或字符串文字运算符,您可以从文字中显式构造std::string
object ,使用std::string("Add")
等表达式代替"Add"s
.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.