c++程序设计,输入一个字符串和一个字符,查找并输出字符在字符串中的首位,如果没有则输入-1
时间: 2024-05-07 22:21:09 浏览: 13
以下是一个简单的C++程序,可以实现你的需求:
```cpp
#include <iostream>
#include <string>
using namespace std;
int main() {
string str;
char ch;
cout << "请输入一个字符串:";
getline(cin, str); // 使用getline获取一整行字符串
cout << "请输入一个字符:";
cin >> ch;
size_t pos = str.find(ch); // 在字符串中查找字符
if (pos != string::npos) { // 如果找到了,输出位置
cout << "字符 " << ch << " 在字符串中的位置为:" << pos << endl;
} else {
cout << "字符 " << ch << " 在字符串中不存在!" << endl;
}
return 0;
}
```
运行程序后,你可以输入一个字符串和一个字符,程序将输出字符在字符串中的位置或者提示字符不存在。注意,在字符串中的位置是从0开始计数的,如果输出-1表示字符不存在。
相关问题
C++程序设计输入一个字符串和一个字符,查找并输出字符在字符串中首次出现的位置,如果没有则输出-1
下面是一个用 C++ 实现的例子:
```cpp
#include <iostream>
#include <string>
using namespace std;
int main() {
string str;
char ch;
cout << "请输入一个字符串:";
getline(cin, str);
cout << "请输入一个字符:";
cin >> ch;
int pos = str.find(ch);
if (pos == string::npos) {
cout << "-1" << endl;
} else {
cout << pos << endl;
}
return 0;
}
```
运行程序后,会提示用户输入一个字符串和一个字符,然后查找并输出字符在字符串中首次出现的位置。如果没有找到该字符,则输出-1。例如,输入字符串 "hello world" 和字符 'w',则输出结果为 6。如果输入字符串 "hello world" 和字符 'z',则输出结果为 -1。
c++ 输入一个字符串和一个字符,查找并输出字符在字符串中首次出现的位置,如果没有则输出-1
下面是 C++ 的代码实现:
```cpp
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str;
char ch;
cout << "请输入一个字符串:";
getline(cin, str);
cout << "请输入一个字符:";
cin >> ch;
int pos = str.find(ch);
if (pos != string::npos) {
cout << "字符\"" << ch << "\"在字符串中首次出现的位置是:" << pos << endl;
} else {
cout << "字符串中没有出现\"" << ch << "\"这个字符!" << endl;
}
return 0;
}
```
使用 `string` 类型的 `find()` 函数查找字符在字符串中首次出现的位置,如果没有找到则返回 `string::npos`。如果找到了,就输出位置;否则就输出提示信息。