在C++中,要想判断输入的string类型的字符串与"fgh"是否相等应该用什么语句来实现
时间: 2024-05-12 13:20:32 浏览: 14
可以使用字符串比较函数`strcmp`或者字符串对象的`compare`函数来判断。具体实现如下:
使用`strcmp`函数:
```c++
#include <iostream>
#include <cstring>
using namespace std;
int main() {
string str;
cin >> str;
if (strcmp(str.c_str(), "fgh") == 0) {
cout << "字符串相等" << endl;
}
else {
cout << "字符串不相等" << endl;
}
return 0;
}
```
使用字符串对象的`compare`函数:
```c++
#include <iostream>
#include <string>
using namespace std;
int main() {
string str;
cin >> str;
if (str.compare("fgh") == 0) {
cout << "字符串相等" << endl;
}
else {
cout << "字符串不相等" << endl;
}
return 0;
}
```
这两种方法都可以判断输入的字符串是否与"fgh"相等。其中,`strcmp`函数需要将字符串转换为C风格的字符串,而`compare`函数则直接比较字符串对象。
相关问题
运用布尔类型判断输入的字符串是否与判断的字符串相等怎么判断
可以使用C++中的字符串比较函数`strcmp()`来判断输入的字符串是否与某个字符串相等。`strcmp()`函数会比较两个字符串,并返回一个整数值。如果两个字符串相等,则返回值为0;如果第一个字符串小于第二个字符串,则返回值小于0;如果第一个字符串大于第二个字符串,则返回值大于0。因此,可以使用如下代码进行判断:
```c++
#include <iostream>
#include <cstring>
using namespace std;
int main() {
string input_str = "hello";
string judge_str = "world";
if (strcmp(input_str.c_str(), judge_str.c_str()) == 0) {
cout << "输入的字符串与判断的字符串相等" << endl;
} else {
cout << "输入的字符串与判断的字符串不相等" << endl;
}
return 0;
}
```
在上述代码中,首先使用了C++中的字符串类型`string`来定义了两个字符串变量`input_str`和`judge_str`。然后,通过`strcmp()`函数比较了这两个字符串的值,如果相等则输出"输入的字符串与判断的字符串相等",否则输出"输入的字符串与判断的字符串不相等"。需要注意的是,`strcmp()`函数的参数需要传入C风格字符串,因此需要使用`c_str()`函数将`string`类型转换为C风格字符串。
在c++中 string off = "OFF";补充代码判断输入的字符串是否是“OFF”
可以使用C++的字符串比较函数`std::string::compare()`来判断输入的字符串是否是“OFF”。具体代码如下:
```
#include <iostream>
#include <string>
using namespace std;
int main() {
string input;
cout << "请输入字符串:";
cin >> input;
string off = "OFF";
if (input.compare(off) == 0) {
cout << "输入的字符串是OFF" << endl;
} else {
cout << "输入的字符串不是OFF" << endl;
}
return 0;
}
```
在上面的代码中,我们首先定义了一个字符串`input`来存储用户输入的字符串,然后定义了另一个字符串`off`来存储“OFF”。接着,我们使用`std::string::compare()`函数比较`input`和`off`是否相等,如果相等,则输出“输入的字符串是OFF”,否则输出“输入的字符串不是OFF”。需要注意的是,`std::string::compare()`函数返回值为0表示两个字符串相等。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)