C++字符串拆分与时间格式化函数两个实现

// ConsoleApplication1.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#pragma warning(disable:4996);

#include 
#include  
#include  
#include  
#include 
#include 
#include 
#include 

using namespace std;

vector<string> readLines(string path) {
    vector<string> vs;
    ifstream myfile(path);
    if (!myfile.is_open()) {
        cout << "Failed to open file." << endl;
        return vs;
    } 
    string temp;
    while (getline(myfile, temp))
    { 
        vs.push_back(temp);
    }
    myfile.close();

    return vs;
}

vector<string> split(string s, char ch)
{
    s.push_back(ch);
    int start = 0, end = 0, size = s.size();
    vector<string> vs;

    for (int i = 0; i < size; i++)
    {
        if (s[i] == ch)
        {
            end = i;
            string temp = s.substr(start, end - start);
            start = i + 1;
            vs.push_back(temp);
        }
    }
    return vs;
}

string getTime()
{
   time_t timep;
   time(&timep);
   char tmp[64];
   strftime(tmp, sizeof(tmp), "%Y-%m-%d %H:%M:%S", localtime(&timep));
   return tmp;
}

int main()
{
    auto vs = readLines("D:\\data\\test.txt");
    cout << vs.size() << endl;

    for(auto s: split("hello, how are you ?", ' '))
        cout<<s<<endl;

    ios state(nullptr);

    cout << "The answer in decimal is: " << 42 << endl;

    state.copyfmt(cout); // save current formatting
    cout << "In hex: 0x" // now load up a bunch of formatting modifiers
        << hex
        << uppercase
        << setw(8)
        << setfill('0')
        << 42            // the actual value we wanted to print out
        << endl;
    cout.copyfmt(state); // restore previous formatting
    printf("state: %d.\n", 0);
    // std::cout << std::format("Hello {}!\n", "world");

    ostringstream ostr;
    ostr << "d = "<<123<<", f = " << 12.345 << ", test format" << endl;
    string str = ostr.str();
    cout << ostr.str().c_str();


    //char  buffer[200], s[] = "computer", c = 'l';
    //int   i = 35, j;
    //float fp = 1.7320534f;

    //// 格式化并打印各种数据到buffer
    //j = sprintf(buffer, "   String:    %s\n", s); // C4996
    //j += sprintf(buffer + j, "   Character: %c\n", c); // C4996
    //j += sprintf(buffer + j, "   Integer:   %d\n", i); // C4996
    //j += sprintf(buffer + j, "   Real:      %f\n", fp);// C4996 
    //printf("Output:\n%s\ncharacter count = %d\n", buffer, j);

    char s[200];
    int j = sprintf(s, "%8.2f", 123.456);

    cout << "s = " << s <<", length: " << j << endl;

    cout << "current datetime: " << getTime() << endl;
}


109
hello,
how
are
you
?
The answer in decimal is: 42
In hex: 0x0000002A
state: 0.
d = 123, f = 12.345, test format
s =   123.46, length: 8
current datetime: 2020-07-08 08:51:35

C:\Users\pc\source\repos\ConsoleApplication1\Debug\ConsoleApplication1.exe (进程 4128)已退出,代码为 0。
要在调试停止时自动关闭控制台,请启用“工具”->“选项”->“调试”->“调试停止时自动关闭控制台”。
按任意键关闭此窗口. . .

你可能感兴趣的:(C/C++,字符串,C++,格式化,时间格式化)