Looping through every character in user input

2019-06-13 15:22发布

问题:

Major beginner here, how can I loop through every character in a user-input using:

get(char& c)

I'd like to use it in a loop to do something with each character (incuding whitespace), but I can't get it to work at the moment.

If you can do so, please provide sample code.

Thanks

Here is what I have right now:

for (char& c : cin.get(char& c)) { 
    cout << c;
}

回答1:

Personally I would write it like this;

std::string s;
while(std::getline(std::cin, s)) {
    for(char c : s) {
        std::cout << c;
    }
}

Although don't forget to account for the '\n' delimeter should you want to keep it. Note that unless you turn of terminal buffering (non standard), you will only get input on a line by line basis anyway.

Note, you can end the loop by signalling an end of file. On linux the user must press Ctrl + d.

Else you can add some logic to the loop and break. For example

if(c == 'q') break;


回答2:

you can have a loop on the entered character, until the entered character is enter (Ascii code 13)

char c;

while ((intVal = (int)cin.get(c)) != 13){
...do processing on the character 'c'
}

or use

char c;
    int intVal=0;

    while ((c = cin.get()) != 13){
    ...do processing on the character 'c'
    }


标签: c++ get