string应用



一、字符串-数值

#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要熟悉转换

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值