C++ 标准输入 cin 使用

cin 总结:
 //    1.  cin >> xxx  并且 cin会忽略 空格  回车 tab 这些
//
//          a.需要看xxx是什么数据类型,如果是int  当输入字符时,相当于0
//            int a;
//            cin >> a;  //输入 'a'
//            printf("%d",a);   //打印出  0
//
//          b. 如果xxx是string 或者 char[]
//              则 接受一个字符串,遇“空格”、“TAB”、“回车”都结束
//              string str;
//              cin >> abc;   //输入 Hello the world
//              cout << abc << endl;   //打印 Hello
//          
//   2.char ch = cin.get();
//    和  char ch;
//        cin.get(ch);一样
//          a.可以接收空格 tab 回车
//            而且会将用户的输入的缓冲区保存下来,下次调用cin.get(ch)时,先直接在缓冲区取
//
//          b. char str[20]; 也有输入缓冲区,下次调用直接从缓冲区取,可以接收 空格 tab,
//             按下回车后,不会等待后面 cin.get 的输入
//             cin.get(str,20);  输入 abcdefghijklmnopqrstuvwxyz
//             cout << str << endl;  打印 abcdefghijklmnopqrs (注意,只打印了19个字符)
//             
//  3. string str;
//    if(getline(cin,str))  // 一次读取一行,但是会舍去后面的换行
//      {
//          cout << str << endl;
//      }

//

//按回车显示一行,按其他键没反应

    ifstream in("/Users/mac/Desktop/test.cpp");
    char ch;
    cin.get(ch);
    
    string result;
    numeric_limits<int> temp;
    
    while(true) {
        
        if (ch == '\n') {
            if (getline(in,result)) {
                cout << result;
                cin.get(ch);
            }else
            {
                cout << "打印完毕!" << endl;
                exit(0);
            }
        }else
        {
            cin.ignore(temp.max(),'\n'); //清除当前行
            cin.get(ch);
        }
    } 

例如,统计一个文件以空格分开单词的个数:

// 统计一个文件以空格隔开单词的个数
    ifstream in("/Users/mac/Desktop/test.cpp");
    
    string result;
    
    int n = 0;
    
    while (in >> result ) {
        ++n;
        cout << n << ":\t" << result << endl;
    }
    
    printf("单词的个数为:%d",n);


查找一个文件内,某个单词出现的次数:

    // 统计一个文件中,某一单词出现的次数
    string target;
    int count = 0;
    while (true) {
        count = 0;
        if (cin >> target) {
            
            cout << "您要找的是" << target << endl;
            
            ifstream in("/Users/mac/Desktop/my.txt");
            
            string temp;
            while (in >> temp) {
                if (temp == target) {
                    ++count;
                }
            }
            cout << "包含" << count << "个" << target << endl;
            
            cin.clear();
            cin.sync();
        }
    }


  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值