c++琐碎
记录点刚学到的, 不成体系
判断浮点数为0
#include <cmath>
float a=1.0, b=2.0, c=1.0;
float delta = power(b, 2) - 4*a*c //使用数学运算, 计算差
//比较float为0时, 不能直接delta==0, 要判断其绝对值小于某个很小的数.
if (fabs(delta)<1e-6) // fabs, 对float求绝对值.
{
cout << "r0==r1"
}
int 转 string
#include <string>
#include <sstream> //使用stringstream需要这个库
#include <iostream>
int main()
{
//int转string, 使用stringstream
std::stringstream str_stream;
int i = 700;
int j = 800;
str_stream << i << j; //使用stringstream将两个int拼接.
std::string s0 = str_stream.str(); //将stringstream转为string.
std::cout << "s0=" << s0 << std::endl; //输出 s0=700800
//int转string, 使用itoa, 好像不好用, 算了.
//int num = 100;
//char str0[25];
//char str1[25];
//std::itoa(num, str0, 10); //参数: 待转int, 输出char, 进制
//std::itoa(num, str1, 16); //参数: 待转int, 输出char, 进制
//std::cout << "str0=" << str0 << std::endl;
//std::cout << "str1=" << str1 << std::endl;
//string转int, 使用atoi
std::string s1 = "700800";
int k = std::atoi(s1.c_str());
std::cout << "k+1=" << k+1 << std::endl; //输出 k+1=700801
return 0;
}
获取系统命令的标准输出
#include <vector>
#include <string>
#include <iostream>
std::vector<std::string> run_cmd(const char cmd[])
{
using namespace std;
vector<string> all_lines;
FILE * pFile;
pFile = popen(cmd, "r");
if (pFile==NULL)
{
cout << "error." << endl;
}
else{
char line[500];
while(fgets(line, sizeof(line)-1, pFile)!=NULL)
{
all_lines.push_back(line);
}
}
pclose(pFile);
return all_lines;
}
int main()
{
using namespace std;
string cmd = "dir";
auto all_lines = run_cmd(cmd.c_str());
for(int i=0; i<all_lines.size(); i++)
{
cout << all_lines[i] << endl;
}
}