c++程序设计,输入一个字符串和一个字符,查找并输出字符在字符串中首次出现的位置,如果没有,则输出-1,用cin和cout
时间: 2023-06-17 15:04:52 浏览: 44
以下是一个示例代码:
```c++
#include <iostream>
#include <string>
using namespace std;
int main() {
string str;
char ch;
int pos = -1;
cout << "请输入一个字符串:";
getline(cin, str);
cout << "请输入一个字符:";
cin >> ch;
for (int i = 0; i < str.length(); i++) {
if (str[i] == ch) {
pos = i;
break;
}
}
cout << "字符在字符串中首次出现的位置是:" << pos << endl;
return 0;
}
```
首先通过 `getline()` 函数输入一个字符串,再用 `cin` 输入一个字符。然后使用 for 循环遍历字符串,如果找到了该字符,则将其位置赋值给 `pos`,并且直接跳出循环。最后输出 `pos` 的值即可。
需要注意的是,如果输入的字符串中包含空格,需要使用 `getline()` 函数进行输入。
相关问题
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++
以下是一个示例代码:
```c++
#include <iostream>
#include <string>
using namespace std;
int main() {
string arr[] = {"hello", "world", "test", "code"};
char target = 'e';
int index = -1;
// 遍历字符串数组,查找目标字符
for (int i = 0; i < sizeof(arr) / sizeof(arr[0]); i++) {
if (arr[i].find(target) != string::npos) {
index = i;
break;
}
}
// 输出结果
if (index == -1) {
cout << "Target character not found in array." << endl;
} else {
cout << "Target character found at index " << index << " in array." << endl;
}
return 0;
}
```
在上述代码中,我们首先定义了一个字符串数组 `arr` 和一个目标字符 `target`。然后我们遍历整个数组,对于每个字符串都调用 `find` 函数查找目标字符。如果找到了目标字符,我们就记录下当前字符串在数组中的下标。最后根据记录的下标输出结果。如果目标字符没有出现在数组中,我们就输出一个提示信息。
相关推荐
![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)