返回顶部

收藏

[C++] 用cin获取用户输入

更多
#include <iostream>
#include <string>
#include <sstream>

using namespace std;

int main() {

    string input = "";

    // How to get a string/sentence with spaces
    cout << "Please enter a valid sentence (with spaces):\n>";
    getline(cin, input);
    cout << "You entered: " << input << endl << endl;

    // How to get a number.
    int myNumber = 0;

    while (true) {
        cout << "Please enter a valid number: ";
        getline(cin, input);

        // This code converts from string to number safely.
        stringstream myStream(input);
        if (myStream >> myNumber)
            break;
        cout << "Invalid number, please try again" << endl;
    }
    cout << "You entered: " << myNumber << endl << endl;

    // How to get a single char.
    char myChar = { 0 };

    while (true) {
        cout << "Please enter 1 char: ";
        getline(cin, input);

        if (input.length() == 1) {
            myChar = input[0];
            break;
        }

        cout << "Invalid character, please try again" << endl;
    }
    cout << "You entered: " << myChar << endl << endl;

    cout << "All done. And without using the >> operator" << endl;

    return 0;
}

标签:cpp,cin

收藏

0人收藏

支持

0

反对

0

相关聚客文章
  1. dutor 发表 2011-11-18 08:50:37 [C++]对象中使用pthread线程
  2. ceeji 发表 2013-04-10 15:44:12 模板类 Stack C++ 实现(链表版)
  3. 楞伽山人 发表 2014-12-04 15:59:31 从语言本身谈语言
  4. 博主 发表 2015-06-15 13:29:33 Unix 编程之进程控制
  5. 博主 发表 2015-06-15 00:00:00 Optimizing&#32;CPP&#58;&#32;The&#32;Costs&#32;Of&#
  6. EricMittelette 发表 2016-08-23 20:23:10 Range-v3 on MSVC is Available on GitHub
  7. zhu329599788@126 发表 2017-01-17 13:34:27 cpp 参考手册
  8. bastengao 发表 2017-12-26 00:00:00 在 Go 语言中调用 C++ 代码
  9. dutor 发表 2012-03-15 13:09:17 g++优化触发的bug一枚
  10. ceeji 发表 2013-04-11 18:22:01 反转单向链表的四种实现(递归与非递归,C++)
  11. Tony Su 发表 2014-10-25 14:39:19 Qt 自定义鼠标样式 QCursor
  12. bigwhite 发表 2015-07-01 06:06:20 Golang程序配置方案小结

发表评论