您的位置:首页 > 编程语言 > C语言/C++

C++ 标准输入 cin 使用

2013-07-12 01:44 781 查看
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();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: