C++杂记(二)

2018-04-07  本文已影响0人  zjh3029

1.C++函数参数个数不定(http://blog.csdn.net/huangwwu11/article/details/44999349)

参数为同一种类型的:initializer_list<type> lst
 有几个方法可以调用:lst.size();lst.begin();lst.end()

参数为不同类型的
    用省略号指定参数列表:
        void fun(...);
        void fun(param_list, ...);

2.查找指定字符:

char a[]="abcd谢谢采纳"
strstr(a,"谢谢");
存在返回第一次出现的位置,不存在返回NULL
string str= "元芳,你怎么看?"
 
size_t pos = str.find("元芳");
 
asser(pos != string::npos);

3.txt文档删除整行:

#include <fstream>
#include <string>
int main(void)
{
    ifstream fi("1.txt", ofstream::in);
    ofstream fo("2.txt", ofstream::out);
    string buf;
    string s1 = "zhangxiang";
    string s2 = "天朝";
    if (fi.is_open() && fo.is_open())
    {
        while (true)
        {
            if (!(fi >> buf)) break;
            if (buf == s1 || buf == s2) continue;
            fo << buf << endl;
        }
        fi.close();
        fo.close();
    }
    return 0;
}

4.打开文件需要ofstream和ifstream, 一个是读, 一个是写. 所以, 要复制需要这样

#include <fstream>
using namespace std;
 
int main()
{
    ifstream fin("input.txt");
    ofstream fout("output.txt");
    char data;
     
    if (!fin || !fout)
        return 0;
         
    while(!fin.eof())
    {
        fin>>data;
        fout<<data;
    }
 
    return 0;
}

5.输出结构体:

#define Name(X) #X
#define Out(X) {string xname=Name(X);cout<<xname<<": "<<X<<endl;}
void out(tWAVEFORMATEX *waveFormat)
{
    Out(waveFormat->wFormatTag);
    Out(waveFormat->nChannels);
    Out(waveFormat->nSamplesPerSec);
    Out(waveFormat->nAvgBytesPerSec);
    Out(waveFormat->nBlockAlign);
    Out(waveFormat->wBitsPerSample);
    Out(waveFormat->cbSize);
}

6.MFC 中 CString 与 std::string 如何相互转换

CString bb,aa="你好";
string a,b="你好";

CString ->string
a=CT2A(aa);

string->CString
bb=CA2T(b);
上一篇 下一篇

猜你喜欢

热点阅读