返回顶部

收藏

[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. 博主 发表 2000-01-01 00:00:00 CPP Notes
  2. Bruce 发表 2014-01-01 11:35:48 Linux C++开发入门
  3. 李瑾 发表 2014-12-14 04:21:08 Memory 4
  4. Bruce 发表 2014-01-01 11:35:48 Linux C++开发入门
  5. bigwhite 发表 2016-05-16 13:11:54 理解Unikernels
  6. zhu329599788@126 发表 2016-12-07 01:30:52 用PHP-CPP写php的扩展
  7. EricMittelette 发表 2017-10-24 00:32:17 Vcpkg: Using multiple enlistments
  8. OWenT 发表 2015-01-08 14:03:42 tolua++内存释放坑
  9. 博主 发表 2014-09-13 00:00:00 Before_write_cpp
  10. Tony Su 发表 2015-06-04 08:47:27 Windows Socket C/S 多线程通信程序
  11. 阿元1985 发表 2015-11-23 15:03:48 [转载]cin.ignore()函数的用法
  12. OWenT 发表 2016-07-31 09:23:34 游戏服务器的不停服更新

发表评论