Looping through every character in user input

天大地大妈咪最大 提交于 2020-01-03 06:03:06

问题


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


来源:https://stackoverflow.com/questions/20710172/looping-through-every-character-in-user-input

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!