文章目录
一、字符串-数值
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
//输入流:
template<class T>
inline T fromString(const string str){
istringstream iss(str);//创建字符串输入流
T v;
iss>>v;//从字符串输入流读取变量v
return v;
}
int main(){
int v1=fromString<int>("5");
cout<<v1<<endl;
double v2=fromString<double>("1.2");
cout<<v2;
return 0;
}
二、字符串-数值
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
//输入流:
template<class T>
inline T fromString(const string str){
istringstream iss(str);//创建字符串输入流
T v;
iss>>v;//从字符串输入流读取变量v
return v;
}
int main(){
int v1=fromString<int>("5");
cout<<v1<<endl;
double v2=fromString<double>("1.2");
cout<<v2;
return 0;
}
三、2019-2
四、
#include <iostream>
#include<string>
using namespace std;
int func(char *str){
int d,num=0,len;
len=sizeof(str);
while(*str!='\0'){
d=int((*str)-'0');//1 d指向当前char
//2 char数组长度
for(int i=0;i<len-1;i++){//3
d=d*10;
}
num+=d;
len--;//长度-1
str++;//5
}
return num;
}
int main(){
char str1[]="23652637";
cout<<func(str1)<<endl;
return 0;
}
五、随机生成十个数并转换格式输入文件
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <ctime>
#include <sstream>
using namespace std;
//数值转换为字符串
string toString(int &x){
ostringstream os;
os<<x;
return os.str();
}
int main(){
srand(time(0));
int a[10]={0};
ofstream os("pay.txt",ios_base::out);
for(int i=1;i<=10;i++){
a[i]=rand()%(100000-10)+10;
cout<<a[i]<<" ";
os<<toString(a[i])<<endl;
}
os.close();
return 0;
}
六、输入 n 个十进制数转换成二进制写到文件,n 是随机得到
//2010_1:输入 n 个十进制数转换成二进制写到文件,n 是随机得到
#include <iostream>
#include <string>
#include <fstream>
#include<algorithm>
using namespace std;
//10进制转2进制字符串的函数,没有考虑负数情况
string toBinary(int d){
string s;
if (d == 0)
return "0";
while (d){
s += (d%2 > 0) ? "1":"0";
d = d/2;
}
reverse(s.begin(), s.end()); //字符串逆置
return s;
}
int main(){
ofstream os("erjinzhi1.txt");
if (!os) {
cerr << "File cannot be opened!\n";
exit(1);
}
int n;
cout << "Enter the n:\n";
cin >> n;
int decimal;
while (n > 0) {
cout << "Please enter a decimal number:\n";
cin >> decimal;
os << toBinary(decimal) << endl; //写入文件
n--;
}
return 0;
}
总结
见pdf文件中的连接以及字符串常用函数
string要熟悉转换