所以我一直在寻找,但无法找到我想做的事情的解决方案。基本上用户输入的内容就像" asdasdasd"我需要通过每个符号来检查它是否是一个'并且需要在它到达char结束后停止循环。我做到了这一点并且它有效,它逐个输出了char符号,但是在这种情况下我无法停止循环,我尝试在最后添加另一个char并使其成为特定的&像#34;"并使用它来停止循环,但后来我需要使用char o [],它按照那里的符号来制动符号。需要帮助..任何输入将不胜感激。
#include <iostream>
using namespace std;
int main(){
char o;
cout<<"input: "; cin>>o;
while(o!= '\0'){
cout<<o<<"\n";
cin >> o;
}
return 0;
}
答案 0 :(得分:1)
当我理解你的问题时,你会输入一个像“ahobansodfb”这样的字符串,然后在特定的字符后搜索?如果是,这是一个小例子:
#include <iostream>
using namespace std;
int main() {
string input;
char search;
int findPos = 0, countOfSearchedChars = 0;
cout << "input searched char: ";
cin >> search;
cout << "input string: ";
cin >> input;
while((findPos = input.find_first_of(search, findPos)) != string::npos){
cout << "Find searched char on pos: " << findPos << endl;
++findPos;
++countOfSearchedChars;
}
if(countOfSearchedChars == 0)
cout << "Char: " << search << " not found in: " << input << endl;
else
cout << "Char: " << search << " found: " << countOfSearchedChars << " time/s in string: " << input << endl;
}
解释:while((findPos = input.find_first_of(search, findPos)) != string::npos)
input.find_first_of(search, findPos)
找到搜索到的字符所在的第一个位置。如果未找到char,则返回string::npos
(18446744073709551615)
所以我们循环这么长的返回值不是string :: npos:!= string::npos
编辑以回答评论问题:
迭代字符串的可能性:
std::string str = "aabaaba";
for(char& c : str) {
if(c == 'a'){
//it's a
} else if(c == 'b') {
//it's b
}
}
std::string str = "abaaba;
for(std::string::iterator it = str.begin(); it != str.end(); ++it) {
if(*it == 'a'){
//it's a
} else if(*it == 'b') {
//it's b
}
}
答案 1 :(得分:0)
感谢所有的答案!,你们得到了很大的帮助,这段代码将为我做,继续研究它的作用x.x
std::string str = "abaaba;
for(std::string::iterator it = str.begin(); it != str.end(); ++it) {
if(*it == 'a'){
//it's a
} else if(*it == 'b') {
//it's b
}
}