C++ strcmp C+中的错误+;?
我编写了以下代码来比较两个字符串。但即使两个字符串相同,或1大于2,输出也是错误的。谁能告诉我错误在哪里C++ strcmp C+中的错误+;?,c++,C++,我编写了以下代码来比较两个字符串。但即使两个字符串相同,或1大于2,输出也是错误的。谁能告诉我错误在哪里 // String Conversion Functions /* Standard Library (to be added): string.h*/ /*Prototype: int strncmp(const char *s1, const char *s2); Description: Compares string s1 to s2. Returns a negative
// String Conversion Functions
/* Standard Library (to be added): string.h*/
/*Prototype: int strncmp(const char *s1, const char *s2);
Description: Compares string s1 to s2. Returns a negative
number if s1 < s2, zero if s1 == s2 or a
positive number if s1 > s2.*/
#include<iostream>
#include<string.h>
using namespace std;
main()
{
char string1[100];
char string2[100];
int result;
cout<<"Please enter first string: ";
cin>>string1;
cout<<"Please enter second string: ";
cin>>string2;
cout<<'\n';
result = strcmp(string1, string2); //answer should be in int type variable
//using if statements to compare different cases.
//int strncmp(const char *s1, const char *s2);
if(result > 1)
{
cout<<"1st string is greater than 2nd string"<<endl;
//function returns a +ve number if s1 > s2.
}
else if(result == 0)
{
cout<<"1st string is equal to 2nd string"<<endl;
//function returns 0 if s1 == s2.
}
else //if result < 1
{
cout<<"1st string is less than 2nd string"<<endl;
//function return a -ve number if s1 < s2.
}
}
//字符串转换函数
/*标准库(待添加):string.h*/
/*原型:int-strncmp(常量字符*s1,常量字符*s2);
描述:比较字符串s1和s2。返回负数
如果s1s2,则为正数*/
#包括
#包括
使用名称空间std;
main()
{
charstring1[100];
字符串2[100];
int结果;
coutstring1;
coutstring2;
cout模板:int strcmp(常量字符*str1,常量字符*str2);
strcmp()将C字符串str1与C字符串str2进行比较
1.返回值0
不匹配的第一个字符在ptr1中的值大于在ptr2中的值
行if(结果>1)
应该是if(结果>0)<代码> > <代码>结果> 1代码>结果> 0代码>代码>比较两个不同字符串中的字符数吗?是的,如果它们有不同的字符数,它们不相等。我尝试了你的程序,当字符串相同时,它工作正常。这不是正确的C++;应该是代码> int()。
以确保有效。