C++ 控制台

2018-03-24 15:29 更新

学习C++ - C++控制台

读取字符到文件结尾


#include <iostream> 
int main() 
{ 
     using namespace std; 
     char ch; 
     int count = 0; 
     cin.get(ch);        // attempt to read a char 
     while (cin.fail() == false)  // test for EOF 
     { 
          cout << ch;     // echo character 
          ++count; 
          cin.get(ch);    // attempt to read another char 
     } 
     cout << endl << count << " characters read\n"; 
     return 0; 
} 

上面的代码生成以下结果。

使用cin.get()读取字符


#include <iostream>
int main(void)
{
    using namespace std;
    int ch;                         // should be int, not char
    int count = 0;

    while ((ch = cin.get()) != EOF) // test for end-of-file
    {
        cout.put(char(ch));
        ++count;
    }
    cout << endl << count << " characters read\n";
  return 0; 
}

上面的代码生成以下结果。



以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号