[英]Checking if an input string is a number and in C++ and, if so, converting it to an int (regex?)
我覺得這是一個非常基本的問題,但是我已經在互聯網上搜索了一個多小時,但沒有找到答案。
我正在編寫一個將輸入作為字符串的文本接口。 如果輸入字符串是數字,我想將字符串轉換為整數並將其壓入我創建的堆棧中。
文本界面的代碼如下:
#include <iostream>
#include "textInterface.h"
#include "Stack.h"
#include <string>
#include <regex>
using namespace std;
void Interface(){
Stack stack = Stack();
string input;
cout << "Please enter a number or operation";
cin >> input;
if (input == "."){
cout << stack.pop();
} //this pops the stack
if (input == "+"){
int a = stack.pop();
int b = stack.pop();
int c = a + b;
stack.push(c);
} //pops the first two things off the stack, adds them, and pushes the result
if (input == "-"){
int a = stack.pop();
int b = stack.pop();
int c = a - b;
stack.push(c);
} //pops the first two things off the stack, subtracts them, and pushes the result
if (input == "*"){
int a = stack.pop();
int b = stack.pop();
int c = a * b;
stack.push(c);
} //pops the first two things off the stack, multiplies them, and pushes the result
if (input == ".s"){
cout << stack.count();
} //returns the size of the stack
if (regex_match(input, "[0-9]")){
int num;
stringstream convert(input);
convert >> num;
stack.push(num);
} //This is the part with the error!!!
}
就像我說的,我想檢查輸入是否為數字,如果是,則將字符串轉換為int並將其壓入堆棧。 我以前使用過正則表達式,但是已經有一段時間了,並且它是在Python中使用的(我對C ++還是陌生的)。 我知道我的regex_match格式不正確,是否有人對如何使其正確無任何建議,或者有閱讀資源的建議?
不要檢查它是否看起來像整數,然后將其轉換為整數。 而是將其轉換為整數,看看是否可行。 使用std::stoi
(或stol
或stoll
,具體取決於您期望的數字大小。)(在<string>
):請參見此處 。
如果無法將字符串轉換為指定大小的整數,則將引發異常,因此您必須在try
內執行該函數。 (如果您是pythonista,則應熟悉該樣式。)
另外,如果有一個數字但它沒有占用整個字符串(即結尾的垃圾),則將指向第二個參數的size_t
設置為第一個未使用字符的索引,因此,如果要檢查整個字符串是一個數字,還應該檢查以確保返回的索引是輸入字符串的大小。
如果您對異常(即使是標准庫拋出的異常)不滿意,則可以只使用基礎標准c函數, strtol
和friends。 它們具有相似的接口,但是使用結合設置errno
的任意值返回來嘗試通信失敗。 就我個人而言,我認為異常接口不太友好,但與往常一樣,口味也有所不同。
我贊成您的問題,因為我有同樣的問題,但沒有找到明顯的解決方案。 我開發了一個有缺陷的解決方案,但對於常見情況來說已經足夠了。 從Google進行搜索時,肯定仍然缺少答案。 因此,出於對人類的了解,我將在此處發布我的解決方案。
bool StringCtr::IsNumeric(bool onlyIntegersYieldTrue /*= false*/, int intRadix /*= 0*/) const
{
_ASSERT(intRadix == 0 || intRadix >= 2 && intRadix <= 36);
bool const acceptsFloats = !onlyIntegersYieldTrue;
bool ok = false;
if (!Empty())
{
char* pEnd = 0;
long li1;
li1 = strtol(Cstr(), &pEnd, intRadix);
ok = ! (li1 == 0L && pEnd == Cstr());
if (!ok && acceptsFloats)
{
double d1;
d1 = strtod(Cstr(), &pEnd);
ok = ! (d1 == 0.0 && pEnd == Cstr());
}
if (ok && !acceptsFloats)
{
ok = ok && !Contains(".");
ok = ok && !Contains("e");
}
}
return ok;
}
所以這是我的字符串類的一個方法,我相信其他從那里調用的方法都具有足夠的自我解釋。 這試圖使用能夠接受許多格式的標准C標記器(strtol)。 實際上,這是要特別小心的事情,因為例如使用0(自動)基數時,以0開頭的數字將被解釋為八進制基數。 否則它很方便,因為它將識別0x ..十六進制表示法模式,並區分整數和浮點數。 它甚至應該理解指數符號,例如“ -1.05e12”。
無論如何,這取決於您真正需要的解析能力,您認為用戶希望程序識別哪種符號約定? 最后,不要聽別人說“很簡單,只需檢查foreach (char c) { ok = c >= '0' && c <= '9'; }
因為這是胡扯,顯然還不夠。負數,浮點數以及我之前提到的所有內容如何?
歡呼!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.