首页 > 代码库 > 1_5

1_5

///////////////////////////////////////////////////////////
// Copyright (c) 2013, ShangHai xxxx Inc.
//
// FileName: 1_5.cpp
//
// Description:
//
// Created: 2014年05月12日 星期一 21时52分50秒
// Revision: Revision: 1.0
// Compiler: g++
//
///////////////////////////////////////////////////////////

//demo 1
#if 1
#include <iostream>
#include <string>

using namespace std;

int main()
{
    string user_name;

    cout<< "Plaese enter your name: ";
    cin>> user_name;

    switch(user_name.size())
    {
        case 0:
            cout<< "Ah, the user with no name. "
                << "Well, ok, hi, user with no name\n";
            break;
        case 1:
            cout<< "A l-character name? Hmm, have you read Kafka?: "
                << "hello, "
                << user_name <<endl;
            break;
        default:
            //字符串长度超过一个字符
            cout<< "Hello, "<< user_name
                << " -- happy to make your acquaintance!\n";
            break;
    }

    return 0;
}
#endif

//demo 2
#if 0
#include <iostream>
#include <iomanip>
#include <cstring>

using namespace std;

int main()
{
    //必须分配一个大小固定的空间
    const int nm_size = 128;
    char user_name[nm_size];
    cout<< "Please enter your name: ";
    cin>>setw(nm_size)>>user_name;

    switch(strlen(nm_size))
    {
        // ...这里处理case 0和case 1,方法同前

        case 127:
            // 也许所得的字符串已被setw()舍弃掉部分内容
            cout<< "That is a very big name, indeed --"
                << "we may have needed to shorten it!\n"
                << "In any case,\n";
            // 此处不加break,往下继续执行
        default:
            // 如果符合前述条件,也会执行至此处,因为先前并没有break
            cout<< "Hello, "<<user_name
                << " -- happy to make your acquaintance!\n";
            break;
    }
    
    return 0;
}
#endif