2016-04-20 27 views
0

3 word 12 with wordのような文字列をintに変換するにはをC++に使用しないで312しか含まれていませんか?私のCodeblodeは私がそれを使用しようとしたときに私にエラーstoi is not a member of stdを与えました。C++は単語と数値の文字列を数値に変換します

ありがとうございます!

+2

コードを投稿してください。[最小、完全で、かつ検証可能な例](http://stackoverflow.com/help/mcve)。 –

+0

'-std = C++ 14'コンパイラスイッチを使用し、コンパイラを[mingw-w64](http://mingw-w64.org)にアップデートしてください(デフォルトのコンパイラスイッチは、クラップです) –

答えて

1

行を通過し、数字以外の記号をスキップします。そして数字の場合は-'0'変換を使用し、*10シフトアプローチを使用します。 E.G .:

#include <stdio.h> 
#include <ctype.h> 
//or cctype to use isdigit() 
#include <string.h> 
//or cstring to use strlen() 

int main() 
{ 
    char str[] = "3 word 12 with word"; // can be any string 
    int result = 0; // to store resulting number 
    // begin of solution 
    for (int i = 0; i < strlen(str); i++) 
    { 
     if (isdigit(str[i])) 
     { 
      result *= 10; 
      result += str[i] - int('0'); 
     } 
    } 
    // end of solution 
    printf("%d\n", result); 
    return 0; 
} 
0

sが最初の文字列であるとします。

int toInt(string s) { 
    string digits; 
    for(size_t i = 0; i < s.size(); i++) 
     if(s[i] >= '0' && s[i] <= '9') 
      digits.push_back(s[i]); 

    int res = 0; 
    for(size_t i = 0; i < digits.size(); i++) 
     res = res * 10 + digits[i] - '0'; 
    return res; 
} 

先行ゼロは問題になりません。 しかし、結果のdigits文字列に大きな数値が含まれていると、オーバーフローが発生する可能性があります。

1

VolAnd's answerと同じ考えです。ちょうど、その質問にはc++とタグ付けされているので、いくつかのSTLのものを使用します。

そして、この1にboost::adaptors::filter(rng, pred)を使用しては楽しいだろう....あなたが先頭にマイナス記号を許可したい場合には、もう少し面白いが、わずかにそれをやり過ぎ:

#include <iostream> 
#include <numeric> 
#include <string> 
using namespace std; 

int main(){ 
    std::string input("3 word 12 with word"); 

    int num = std::accumulate(input.begin(), input.end(), 0, 
      [](int val, const char elem) { 
       if (isdigit(elem)) { 
        val = val*10 + (elem-'0'); 
       } 
       return val; 
     } 
    ); 

    std::cout << num << std::endl; 
    return 0; 
} 

http://en.cppreference.com/w/cpp/algorithm/accumulate

ノートを参照してください;-)

関連する問題