博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

C++编程思想

Posted on 2023-02-22 13:42  乔55  阅读(32)  评论(0编辑  收藏  举报

命名空间

  • 所有的标准C++标准库都封装在std命名空间中
  • include<iostream.h>相当于:#include<iostread> using namespace std;

C++输出格式控制

void test()
{
    cout << dec << 15 << endl;  // 10f进制输出
    cout << oct << 15 << endl;  // 8进制输出
    cout << hex << 15 << endl;  // 16进制输出
    cout << "hello world"       // 将好几行一块输出
        " i am chinese"
        " i love china" << endl;
}

C++文件读写

  • 为了打开文件进行读写操作,必须包含#include<fstream>
  • 为了读而打开文件,要创建一个ifstream对象,用法与cin相同
  • 为了写而打开文件,需创建一个ofstream对象,用法与cout相同
  • iostream中有一个函数getline,它可以逐行读取字符,遇到换行符结束
  • getline第一个参数是ifstream对象,从中读取内容
  • getline第二个参数是stream对象
  • getline将丢弃换行符而不把它存入string对象中
  • 函数调用完之后,string对象就装载了一些内容
/// @brief 打开文件并每次将一行读进string对象,最后将string对象压入vector,输出vector
void test()
{
    vector<string> v;       // 定义容纳string的vector
    ifstream in("my.cpp");  // 用流对象in打开文件my.cpp
    string line;            // 定义一个string对象
    while (getline(in, line))   // 从流对象in中逐行读取内容,存放在line中 换行符丢弃
    {
        v.push_back(line);      // 将将line对象的内容存放到vector中,
    }
    for (int i = 0; i < v.size(); i++)
    {
        cout << v[i] << endl;   // 输出vector容器每个元素,它的每个元素是一个行string
    }
}
/// @brief 将my.cpp文件的内容分解为由空格分隔的单词,将这些单词存入vector中并输出
void test()
{
    vector<string> words;
    ifstream in("my.cpp");
    string word;
    while (in >> word)
    {
        words.push_back(word);
    }
    for (int i = 0; i < words.size(); ++i)
    {
        cout << words[i] << endl;
    }
}