The inequality of string constants and the copy of strings in C + +

Source: Internet
Author: User
Tags integer strcmp
#include <iostream>

void Main (void)
{
if ("test" = = "Test")
{
cout<< "equal";
}
Else
{
cout<< "Not Equal";
}
}

In the code above, we test that the two string constants for test are equal and, by common sense, should be equal, and that they will get the same conclusion in some procedural languages, but not in C + +.

Why, then?

The answer is here: Because string constants are stored in computer memory, the addresses of two string constants are not the same, so this comparison will naturally not get the results we need, if you want to make comparisons of equality should use STRCMP () the number of the Han to compare!

#include <iostream>
#include <string>
using namespace Std;

void Main (void)
{
if (strcmp ("Test", "Test") ==0)
{
cout<< "equal";
}
Else
{
cout<< "Not Equal";
}
Cin.get ();
}

strcmp () is the prototype of the function, int strcmp (const char* str1,const char* str)

Quite will return an integer equal to 0, which will return a non-0 integer when not equal.

#include <iostream>
#include <string>
using namespace Std;
void Main (void)
{
Char test[]= "Test str!";
Char str[15];
strcpy (str,test);
cout<<str<<endl;

int a[]={1,2,3,4,5};
int b[5];
memcpy (B,a,sizeof (a));
for (int i=0;i<5;i++)
{
cout<<b[i]<< ",";
}
Cin.get ();
}

The strcpy in the above code is used to handle copy of the string Math group, because the string array belongs to the const char*, which is the constant pointer, so it is not possible to use a= "test str!"; , followed by the memcpy used to handle the copy processing of the array at the end of the memcpy, the third parameter is the amount of memory space required for B to be set in memory, and is processed with sizeof (a) *sizeof (int).

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.