BloodyPeach
BloodyPeach

Reputation: 3

c++ reading user inputted char one by one symbol

So I have been searching, but couldn't exactly find a solution for the thing I want to do. Basically User input's a char like "asdasdasd" and I need to go thru each symbol to check if it's 'a', and need to stop the loop after it has reached the end of char. I got this far and it works, it output's the char symbols one by one, but in this case I can't stop the loop, I tried adding another char at the end and make it something specific like "." and use that to stop the loop but then I need to use char o[] which brakes the symbol by symbol thing going on there. Need help.. any input would be appreciated.

#include <iostream>
using namespace std;
int main(){
    char o;
    cout<<"input: "; cin>>o;

    while(o!= '\0'){
        cout<<o<<"\n";
        cin >> o;
    }
    return 0;
}

Upvotes: 0

Views: 1186

Answers (2)

BloodyPeach
BloodyPeach

Reputation: 3

THANKS for all the answers!, you were big help, this code will do for me, going to go research what it does 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
    }
}

Upvotes: 0

Morchul
Morchul

Reputation: 2037

When I understand your question correct you will input a string like "ahobansodfb" and search in there after a specific char? If yes, this is a little example:

#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;
}

Explanation for: while((findPos = input.find_first_of(search, findPos)) != string::npos)

input.find_first_of(search, findPos) find the first place where the searched char lies. When the char doesn't found it returns string::npos (18446744073709551615)

So we loop so long the return value is not string::npos: != string::npos

Edit to answer comment question:
Possibilities to iterate through a string:

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
    }
}

For every character in string

Upvotes: 1

Related Questions