A+B的和D进制

题目描述:其 A+B 和的D进制.

题目不难,主要被输入流是string卡住了,复习一下 string 与 char[] 与int 相关类型的转换


string 转 char[]

#include <iostream>
#include <string>
using std::string;void main()
{
string add_to="hello!";
//std::cout<<add_to;
const string add_on="baby";

const char*cfirst = add_to.c_str();
const char*csecond = add_on.c_str(); 
char*copy = new char[strlen(cfirst) + strlen(csecond) + 1];
strcpy( copy, cfirst);
strcat( copy, csecond);
add_to = copy;
delete [] copy;
std::cout<<add_to<<std::endl;

char[] 转string:

可以直接复制给string


int转string 

通过int 到char[] 再到string

int a= 10002;
char tmp[32];  
sprintf(tmp,"%d",a);
string s2 = tmp;


还有一种通过

#include <sstream>
int main() {
stringstream ss;
 int n = 65535;
     string s;
     ss << n;
     ss >> s;
     cout << s << endl;
...}


关于本题:

/*
 * Main.cpp
 *
 *  Created on: 2015年3月16日
 *      Author: jason
 
 */
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
char tmp[32];
string transfer(long long a,int d) {
	if(a>=d) {

	    sprintf(tmp,"%d",a%d);
		string s2 = tmp;
		return transfer(a/d,d)+s2;
	}
	else {
	    sprintf(tmp,"%d",a);
		string s2 = tmp;
		return s2;
	}
}
int  main(){
	string s;
	char ch[80];
	stringstream ss;
	 int n = 65535;
     string s;
     ss << n;
     ss >> s;
     cout << s << endl;
 
	while(cin.getline(ch,80,'\n')) {
		s = ch;
		int space = 0;
		int x = 0,a,b,d;
		for(int i=0;i<s.length();i++){
			if(s[i]==' '&&space ==0) {
				a = x;
				x = 0;
				space++;
				continue;
			}
			if(s[i]==' '&&space ==1) {
				b = x;
				x = 0;
				space++;
				continue;
			}
            x *=10;
			x = x+ s[i]-'0';

		}
		d = x;
		if(d==1) 
			cout<<"-1";
		else
		cout<<transfer(a+b,d);
	}
return 0;
}






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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值