8.1 C++ 标准输入输出流

发布时间 2023-10-21 15:11:31作者: lyshark

C/C++语言是一种通用的编程语言,具有高效、灵活和可移植等特点。C语言主要用于系统编程,如操作系统、编译器、数据库等;C语言是C语言的扩展,增加了面向对象编程的特性,适用于大型软件系统、图形用户界面、嵌入式系统等。C/C++语言具有很高的效率和控制能力,但也需要开发人员自行管理内存等底层资源,对于初学者来说可能会有一定的难度。

标准输出流: 首先我们演示标准的输入输出,其需要引入头文件<iostream>

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>

using namespace std;

int main(int argc, char* argv[])
{
  char str[] = "lyshark";
  int number = 0;

  cout << "hello: " << str << endl;
  cin >> number;
  if (number == 0)
  {
    cerr << "Error msg" << endl;  // 标准的错误流
    clog << "Error log" << endl;  // 标准的日志流
  }

  int x, y;
  cin >> x >> y;                      // 一次可以接受两个参数
  freopen("./test.log", "w", stdout); // 将标准输出重定向到文件

  system("pause");
  return 0;
}

格式化输出: 在程序中一般用cout和插入运算符“<<”实现输出,cout流在内存中有相应的缓冲区。

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <iomanip>

using namespace std;

int main(int argc, char* argv[])
{
  cout << hex << 100 << endl;             // 十六进制输出
  cout << dec << 100 << endl;             // 十进制输出
  cout << oct << 100 << endl;             // 八进制输出
  cout << fixed << 10.053 << endl;        // 单浮点数输出
  cout << scientific << 10.053 << endl;   // 科学计数法

  cout << setw(10) << "hello" << setw(10) << "lyshark" << endl;  // 默认两个单词之间空格

  cout << setfill('-') << setw(10) << "hello" << endl; // 指定域宽,输出字符串,空白处以'-'填充

  for (int x = 0; x < 3; x++)
  {
    cout << setw(10) << left << "hello" ; // 自动(left/right)对齐,不足补空格
  }

  cout << endl;
  system("pause");
  return 0;
}

单个字符输出: 流对象中,提供了专用于输出单个字符的成员函数put

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <iomanip>

using namespace std;

int main(int argc, char* argv[])
{
  char *str = "lyshark";

  for (int x = 6; x >= 0; x--)
    cout.put(*(str + x));  // 每次输出一个字符
  cout.put('\n');

  system("pause");
  return 0;
}

标准输入流: 通过测试cin的真值,判断流对象是否处于正常状态.

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <iomanip>

using namespace std;

int main(int argc, char* argv[])
{
  float grade;

  while (cin >> grade)
  {
    if (grade >= 85)
      cout << grade << " good" << endl;
  }
  system("pause");
  return 0;
}

读取字符串: 通过getline函数,实现了从输入流中读取一行字符

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <iomanip>

using namespace std;

int main(int argc, char* argv[])
{
  char str[20];
  int x, y, z;

  cin >> x >> y >> z;
  cout << x << y << z;

  cin.getline(str, 20);        // 读入字符遇到\n结束读取
  cout << str << endl;

  cin.getline(str, 20, 'z');  // 读入字符遇到z字符才结束
  cout << str << endl;

  system("pause");
  return 0;
}

IO流实现文件读写: 使用<fstream>文件处理类,实现对文本文件的读写操作.

#include <iostream>
#include <string>
#include <fstream>

using namespace std;

void Write_File(string path, string text)
{
  ofstream ofs;
  //::app = 打开文件后追加 ::trunc = 打开文件后清空
  ofs.open(path, ios::out | ios::app);
  // 判断是否打开成功,成功则写入
  if (ofs.is_open())
    ofs << text << endl;
}

void Read_File(string path)
{
  ifstream ifs;
  
  ifs.open(path, ios::in);
  if (ifs.is_open())
  {
    char buffer[1024];
    while (!ifs.eof())
    {
      ifs.getline(buffer, sizeof(buffer));
      cout << buffer << endl;
    }
  }
}

int main(int argc, char *argv[])
{
  Write_File("c:/lyshark.log", "hello lyshark");
  Write_File("c:/lyshark.log", "hello admin");
  Read_File("c:/lyshark.log");

  system("pause");
  return 0;
}

字符串与数字判断: 判断用户输入的是数字还是字符串,并输出到屏幕上.

#include <iostream>
#include <string>

using namespace std;

int main(int argc, char *argv[])
{
  char ch = cin.peek();        // 获得输入字符
  if (ch >= '0' && ch <= '9')
  {
    int number;
    cin >> number;
    cout << "number is :" << number << endl;
  }
  else
  {
    char buffer[1024];
    cin >> buffer;
    cout << "string is: " << buffer << endl;
  }

  system("pause");
  return 0;
}

输入数字判断案例: 让用户输入数字如果是1-10之间的则结束,否则继续循环

#include <iostream>
#include <string>

using namespace std;

int main(int argc, char *argv[])
{
  int number;
  
  while (true)
  {
    cin >> number;
    if (number > 0 && number <= 10)
    {
      cout << "number is: " << number << endl;
      break;
    }
    cin.clear();    // 重置标志位
    cin.sync();     // 清空缓冲区
  }

  system("pause");
  return 0;
}

IO流实现排序并存盘: 将文件in.log中的整数排序后输出到out.log中.

#include <iostream>
#include <cstdlib>
#include <fstream>

using namespace std;

// 使用qsort排序的回调函数
int MyCompare(const void *x, const void *y)
{
  return *((int *)x) - *((int *)y);
}

int main(int argc, char *argv[])
{
  int Array[10] = { 0 };
  int index = 0;
  // in.log 存放十个数 ==> 5 6 9 2 0 1 3 6 7 9
  ifstream srcFile("c://in.log", ios::in); //以文本模式打开in.txt备读
  ofstream destFile("c://out.txt", ios::out); //以文本模式打开out.txt备写

  // 以空格为单位读出文件中的数据放入数组
  int tmp;
  while (srcFile >> tmp)
    Array[index++] = tmp;

  // 调用排序函数
  qsort(Array, 10, sizeof(int), MyCompare);

  // 输出排序后的数,并写入文件保存
  for (int x = 0; x < 10; x++)
  {
    cout << "Array => " << Array[x] << endl;
    destFile << Array[x] << " ";                // 回写到文件
  }

  srcFile.close();
  destFile.close();

  system("pause");
  return 0;
}

读/写二进制流结构: 假设我们定义student结构,我们使用二进制方式写入到文件中.

#include <iostream>
#include <fstream>

using namespace std;

struct Student
{
  char szName[20];
  int age;
};

int main(int argc, char *argv[])
{
  struct Student stu;

  strcpy(stu.szName, "lyshark");
  stu.age = 33;

  // 将结构中的数据写入到磁盘
  ofstream outFile("c://student.log", ios::out | ios::binary);
  outFile.write((char *)&stu, sizeof(stu));
  outFile.close();

  // 从文件流中读取数据
  struct Student read_stu;
  ifstream inFile("c://student.log", ios::in | ios::binary);
  inFile.read((char *)&read_stu, sizeof(read_stu));
  cout << read_stu.szName << read_stu.age << endl;
  inFile.close();

  system("pause");
  return 0;
}

利用IO流实现文件拷贝: 通过使用get函数实现,从文件中一次读取一个字节,并将其拷贝到另一个文件中.

#include <iostream>
#include <fstream>

using namespace std;

int main(int argc, char *argv[])
{
  ifstream inFile("c://lyshark.exe", ios::binary | ios::in);  //以二进制读模式打开文件
  ofstream outFile("c://test.exe", ios::binary | ios::out);  //以二进制写模式打开文件

  char ch;
  while (inFile.get(ch))  // 每次读取一个字符
  {
    //cout << ch << " ";
    outFile.put(ch);    // 每次写入一个字符
  }
  outFile.close();
  inFile.close();

  system("pause");
  return 0;
}

本文作者: 王瑞
本文链接: https://www.lyshark.com/post/e54e2d59.html
版权声明: 本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!