从字符串转换为int [英] convert from string to int

查看:74
本文介绍了从字符串转换为int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

帮我输出的信息不正确....

#include< iostream>
#include< string>
#include< conio.h>
使用名称空间std;
int main()
{

字符串first,second;
cout<<输入第一个数字"<< endl ;;
cin>第一的; //输入= 123
cout<< endl<<输入第二个数字"<< endl;
cin>第二; //输入= 324

int product =(int)first [2] *(int)second [2];
cout<<产品; //输出必须为12,因为3 * 4 = 12请



getch();
返回0;
}

help me output is not coming in correct....

#include <iostream>
#include <string>
#include<conio.h>
using namespace std;
int main()
{

string first,second;
cout<<"Enter the first number"<<endl;;
cin>> first; // input=123
cout<<endl<<"Enter the Second Number"<<endl;
cin>> second; // input=324

int product= (int) first[2] * (int)second[2];
cout<<product; //output must be 12 because 3*4=12 please



getch();
return 0;
}

推荐答案

您正试图乘以字符代码(0x33 * 0x34,代表"3"和"4").如果要这样做:
You are trying to multiply the character code (0x33*0x34, stands for ''3'' and ''4''). If you want to do so:
int product= (int) (first[2]-''0'') *   (int)(second[2]-''0'');



atoi(first.c_str())



但是您可以只更改firstsecond的类型,并让cin处理它:
首先



But you can just change the type of first and second and let cin handle it:

int first
cin >> first;


string first2 = first [2];
字符串second2 = second [2];
int product = atoi(first2.c_str())* atoi(second2.c_str());
string first2 = first[2];
string second2 = second[2];
int product= atoi(first2.c_str()) * atoi(second2.c_str()) ;


这篇关于从字符串转换为int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆