问题描述
请帮帮我。 strcmp不正常它只返回70,即使2个字符串不同。
pch包含(0.06666,0.0333,0.0666等)
测试包含(0.0333)
Please help me out. strcmp not working properly it's only return "70" even though 2 strings are diffrent.
pch contain(0.06666, 0.0333, 0.0666 and so on)
test contain ("0.0333")
float ReadFile(float Elastmod[], int NumLines,float Elastmod3[])
{
ifstream myReadFile;
char inputfile[_MAX_FNAME ],
Extension[ _MAX_EXT ] = ".CSV";
_makepath(Infilename, "C:", Dir, inputfile, Extension);
myReadFile.open("Rdm1.csv");
char test[] = "0.0333";
char* pch;
char* Token; //DYNAMICALLY ASSIGN ARRAY
Token = new char[NumLines];
int i;
if (myReadFile.is_open())
{
while (!myReadFile.eof())
{
myReadFile.ignore(256,'\n'); // to ignore first Line
myReadFile.getline(Token,256,',');
for(int i=0;i<(NumLines-1);i++)
{
pch = strtok (Token,",");
myReadFile.getline(Token,256,',');
Elastmod[i]= atof(pch) ;
int result= (strcmp (pch,test) == 0);
if (result == 1)
Elastmod3[i]= atof("90");
else if ( result == 0)
Elastmod3[i]= atof("70");
else
Elastmod3[i]= atof("888");
}
}
}
else
{
//cout << "Error opening file";
}
myReadFile.close();
return Elastmod3[NumLines] ;
}
谢谢。
[edit]已添加代码块 - OriginalGriff [/ edit]
Thank you.
[edit]Code block added - OriginalGriff[/edit]
推荐答案
int result= (strcmp (pch,test) == 0);
cout << "Result=" << result << endl;
cout << "Pch=" << pch << endl;
cout << "Test=" << test << endl;
cout << "Strcmp=" << (strcmp(pch,test)) << endl;
看看究竟有什么比较,我认为pch可能不是你想象的那样。
And see what exactly is being compared, I'm thinking that pch may not be what you think it is.
Returns an integral value indicating the relationship between the strings:
A zero value indicates that both strings are equal.
A value greater than zero indicates that the first character that does not match has a greater value in str1 than in str2; And a value less than zero indicates the opposite.
所以你的代码应该是这样的:
So your code is probably supposed to be something like:
int result = strcmp (pch, test);
if (result > 0)
Elastmod3[i]= 90.0;
else if (result == 0)
Elastmod3[i]= 70.0;
else
Elastmod3[i]= 888.0;
请注意,我已经删除了atof电话,这些只是无聊。
And我们在这里:与strcmp的整个比较没有多大意义。您可能想要比较浮点值。在线
Note that I have removed the atof calls, which are just nonesense.
And while we are at it: The entire comparison with strcmp does not make much sense. You probably want to compare the float values. And in line
Elastmod[i]= atof(pch) ;
您已将pch转换为浮动。为什么不直接将该值与另一个值进行比较,例如:
you converted already pch to float. Why don't you just compare that value to another, like:
float test = 0.0333;
...
float pchf = atof (pch);
...
if (pcfh > test)
Elastmod3[i]= 90.0;
else if (pcfh == test)
Elastmod3[i]= 70.0;
else
Elastmod3[i]= 888.0;
还有一条评论:对两个浮点值相等的测试测试在大多数情况下确实没有多大意义。
And one more comment: Test test on equality of two floating point values does in most cases make not much sense.
这篇关于我对strcmp的使用不正常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!