2012-05-07 44 views
2

我想提取字符數組的字符串數值。其實我想提取一些文件管理的文件名中嵌入的數字。例如,如果有一個文件名爲file21那麼我想要這個文件名的十進制數。如何從字符數組中提取數字字符串成員

如何提取這些值?

我嘗試了以下,但它導致意想不到的價值。我認爲這是由於在進行關節手術的同時,從char到int的隱式類型轉換的結果。

char * fname; 
cout<<"enter file name"; 
cin>>fname; 

int filenum=fname[4]%10+fname[5]; 
cout<<"file number is"<<filenum; 

注: 的filenamse嚴格的格式爲fileXXXX是號碼01和99

+1

如果字符串有「A3L5」之類的字符,你想要35嗎? – chris

+0

這段代碼在很多方面都是錯誤的,但是嘗試輸入'std :: string fname;'而不是'char *',然後從中取出。如果用戶只輸入1個字符會發生什麼?噗。 –

+1

@chris:文件名嚴格爲** file22.tx ** – gcmn

回答

2

你需要減去'0'得到一個數字字符的十進制值:

int filenum=(fname[4]-'0')*10+(fname[5]-'0'); 

更重要的是,你應該使用atoi

int filenum = atoi(fname+4); 
+2

爲什麼在有C++選擇時使用'atoi'? – chris

+0

@chris即使與OP手動「解析」數字的想法相比,C++的替代方案也更爲複雜。 'atoi'是C++標準庫的[first class member](http://www.cplusplus.com/reference/clibrary/cstdlib/atoi/),爲什麼不把它用在絕對不是* C++ - ish的東西上開始? – dasblinkenlight

+0

的確,這個問題比C++要多得多。從來沒有不好開始,雖然imo。 – chris

2

之間你得到不確定的行爲,因爲你永遠爲char*分配內存你讀入:

char * fname = new char[16]; //should be enough for your filename format 

或更好,但

char fname[16]; 

而且,你能指望什麼:

fname[4]%10+fname[5]; 

辦?神奇地連接數字?

首先,將第一個字符轉換爲int,將其乘以10,將第二個字符轉換爲int並添加到第一個字符。一個簡單的谷歌搜索char to int會讓你在那裏。

1

我如何可以提取這些價值?

有無數的方法。一種方法是使用std::istringstream

#include <string> 
#include <sstream> 
#include <iostream> 

int main() { 
    std::string fname; 
    std::cout << "Enter file name: "; 
    std::getline(std::cin, fname); 

    int filenum; 
    std::istringstream stream(fname.substr(4,2)); 

    if(stream >> filenum) 
    std::cout << "file number is " << filenum << "\n"; 
    else 
    std::cout << "Merde\n"; 
} 
0

這是最簡單的代碼:

#include <iostream> 
#include <sstream> 
#include <string> 
using namespace std; 
int main() 
{ 
    int filenum; 
    string fname; 
    cout<<"enter file name"; 
    cin>>fname; 

    string str2 = fname.substr(4,2); 
    istringstream(str2) >> filenum; 
    cout<<"file number is"<<filenum; 
    return 0; 
} 
0

如果你輸入的是,很多定義,最簡單的辦法是scanf函數:

int main() 
{ 
    int theNumber = 0; 
    scanf("file%d.txt", &theNumber); 
    printf("your number is %d", theNumber); 
} 

檢查它在行動中,讀取char *而不是stdio:http://codepad.org/JFqS70yI

scanf(和sscanf)也會檢查正確的輸入格式:返回成功讀取的字段數。在這種情況下,如果返回值不是1,那麼輸入是錯誤的。