循环通过用户输入中的每个字符 [英] Looping through every character in user input

查看:116
本文介绍了循环通过用户输入中的每个字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里的主要初学者,如何使用以下方式循环用户输入中的每个字符:

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.

感谢

以下是我现在的情况:

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


推荐答案

this;

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

虽然不要忘记' \\ n'delimeter应该保留它。注意,除非你打开终端缓冲(非标准),否则你只能逐行获得输入。

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.

注意,你可以通过信令文件结束。在linux上,用户必须按Ctrl + d。

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;

这篇关于循环通过用户输入中的每个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆