[英]How to convert a string to an integer in C++?
到目前為止,這是我的代碼:
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
int main()
{
string exp;
cout << "Enter a number and raise it to a power" << endl;
cin >> exp;
int num = exp[0];
int pow = exp[2];
cin.get();
cin.ignore(256,'\n');
}
基本上,我正在嘗試制作一個程序,您可以在其中輸入“ 2 ^ 5”之類的內容,它將為您解決問題。 到目前為止,我已經獲取了字符串的第一個和第三個值,並將它們稱為“ num”和“ pow”。 (數字,冪)如果嘗試“ cout << num;”之類的東西, 它將為您提供十進制的Ascii值。 如何將其轉換為小數?
您可以從cin
直接讀取為整數變量:
int n;
std::cin >> n;
但是您不能以這種方式輸入看起來自然的表情。
要讀取2^5
,可以使用std::stringstream
:
int pos = exp.find('^');
int n;
std::stringstream ss;
if(pos != std::npos){
ss << exp.substr(0, pos);
ss >> n;
}
和第二個變量類似。
此方法在Boost中作為boost::lexical_cast
。
更復雜的表達式需要構建解析器,我建議您閱讀有關此主題的更多信息。
strtol
在這方面非常擅長。 它讀取盡可能多的數字,返回數字,還為您提供了導致其停止的字符的指針(在您的情況下為'^'
)。
int num;
char op;
int pow;
if ((std::cin >> num >> op >> pow) && op == '^') {
// do anything with num and pow
}
您的所有數字似乎都小於10,在這種情況下, exp[0]-'0'
和exp[1]-'0'
就足夠了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.