2016-10-20 25 views
-1

私は、文字列を持っている:増加効率文字列C++から整数を解析

12:56:72

私は3つの数字(を取得する必要があり、、および)。

私がやっている:

int i=0,j=0,k=0,n, p[3]; // p[i] stores each ith value 
char x[], b[]; 
x="12:34:56"; 
n=strlen(x); 
while(i<strlen){ 
     b[k]=x[i]; 
     ++i; 
     ++k; 
     if(x[i==]':'){ 
      p[j]=int(b); 
      ++j; 
      ++i; 
      k=0; 
      char temp[] = b; 
      b=new char[]; 
      delete temp; 
      } 
     } 

は、これは、より効率的に行うことができますか?

+0

どのように文字列を取得していますか?入力ストリームから来ている場合は、それを直接整数に読み込むことができます。 – NathanOliver

+0

私はfstreamを使って入力ストリームからそれを取得しています。どのようにして整数を直接得るのですか? –

+0

数字は常に2桁ですか、それとも1桁の数字ですか? –

答えて

1

「より効率的」にするには、プロファイルする必要があります。ここで

は別のソリューションです:

const std::string test_data("01:23:45"); 
unsigned int hours; 
unsigned int minutes; 
unsigned int seconds; 
char separator; 
std::istringstream input(test_data); 
// Here's the parsing part 
input >> hours >> separator >> minutes >> separator >> seconds; 

これは「より効率的」であるか否かを、測定されなければなりません。
よりシンプルで安全です。

編集1:方法2
プロセッサは、ループまたは枝を好きではないので、我々は最小限にしようとすることができます。 この最適化は完全な入力を文字列として想定しています。

static const char test_data[] = "01:23:45"; 
unsigned int hours; 
unsigned int minutes; 
unsigned int seconds; 
char c; 
unsigned int index = 0; 
hours = test_data[index++] - '0'; 
if (test_data[index] != ':') 
{ 
    hours = hours * 10 + test_data[index++] - '0'; 
} 
++index; // Skip ':' 
minutes = test_data[index++] - '0'; 
if (test_data[index] != ':') 
{ 
    minutes = minutes * 10 + test_data[index++] - '0'; 
} 
++index; // Skip ':' 
seconds = test_data[index++] - '0'; 
if (test_data[index] != ':') 
{ 
    seconds = seconds * 10 + test_data[index++] - '0'; 
} 

最高の最適化を行うには、いくつかの前提が必要です。別の仮定は、文字エンコーディングがUTF8またはASCIIであるということです。 '1' - '0' == 1

+0

これはうまくいきました、ありがとうございます。 –

1

ファイルストリームからデータを読み込んでいるので、そのストリームのoperator >>を利用することができます。 intにデータを入力すると、intに無効な文字が入力されるまでファイルの読み取りが継続されます。これは整数部分を読み込み、ファイルにコロンを残します。この動作のため、私たちは

ifstream fin("filename.ext"); 
int a, b, c; 
char colon; 
while(fin >> a >> colon >> b >> colon >> c) 
{ 
    // do stuff with a, b and c 
} 

を使用することができますし、これがある限り、ファイルが12:56:72の形式の行を持っているとして、行毎にファイルを読み込みます。

+0

これはうまくいきました、ありがとうございます。 私はこれを見た(そして試してみる)前にトーマスの方法を試しました。 私の担当者のために、それは私のアップ票を表示していません。 –

+0

@AgentWeirdo問題ありません。喜んで助ける – NathanOliver

0

それは時計のように見えますが、それでも、あなたはsscanf関数で文字列をスキャンすることができます:

#include <iostream> 

using namespace std; 

int main() 
{ 
    char myclock[] = "10:11:12"; 
    int hours, minutes, seconds; 
    sscanf(myclock, "%d:%d:%d", &hours, &minutes, &seconds); 
    cout << hours << endl; 
    cout << minutes << endl; 
    cout << seconds << endl; 
    return 0; 
} 
0

あなたはC++の機能を使用することを検討してください可能性があります。

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

int main() { 
    size_t i=0,j=0,k=0, p[3]; // p[i] stores each ith value 
    string x("12:34:56"); 
    for (j=0; j<3; j++) { 
     p[j] = stoi(x.substr(k), &i); 
     k += i+1; 
    } 

    for (j =0; j < 3; j++) 
     cout << p[j] << endl; 
}