2015-04-12 44 views
0

我是新來的C++,並提出了這個問題,我真的不知道如何進行。C++搜索號碼的數字

我會得到一個從0-999的數字,我試圖確定數字中是否出現了數字1,4或7。

我試過使用find_first_of(),但我有很多錯誤。

這裏是我到目前爲止的代碼:

double ctemp; 
cin >> ctemp; 
if(ctemp.find_first_of(1)==-1 && ctemp.find_first_of(4)==-1 && ctemp.find_first_of(7)==-1) 
{ 
    cout << "Found digits 1, 4, 7.\n"; 
} 

然而,當我運行此代碼,我得到以下錯誤:

11:18: error: request for member 'find_first_of' in 'ctemp', which is of non-class type 'double'

我試圖改變變量類型爲字符串,但它提出了更多的錯誤和不足。有沒有人有任何方法讓搜索數字更容易?

+0

您需要將您的號碼加載到'std :: string'或將您的double加載到它。 (但如果它是整數,則使用int而不是double) –

+3

字符串是一串字符。數字不是一個數字序列。如果你讀入一個字符串,你需要'find_first_of('1')'。 – molbdnilo

+0

閱讀錯誤信息如何?這一點特別清楚。 – Cthulhu

回答

2

您必須以string或更高版本的形式輸入您的電話號碼,因爲find_first_of()可以在string上工作,所以請將其轉換爲string
它返回匹配的第一個字符的位置。 如果找不到匹配項,則函數返回string::npos(= -1)。

string ctemp; 
cin >> ctemp; 
    if(ctemp.find_first_of('1')!=string::npos && ctemp.find_first_of('4')!=string::npos&& ctemp.find_first_of('7')!=string::npos) 
{ 
    cout << "Found digits 1, 4, 7.\n"; 
} 
+0

你提到'string :: npos',然後不要在你的代碼示例中使用它。 –

+0

,因爲此常數的值爲-1,所以在代碼中寫入-1更短。 – JerryGoyal

+0

較短並不一定意味着更好。 – Chad

3

如果您的號碼是0和999之間的整數,你應該用int,而不是double

解決此問題的一種方法是取模10,直到沒有剩下任何東西。這樣,您將查看該號碼的最小數字(從右到左)。

#include <stdio.h> 

int is_digit_in_number(int digit, int number) 
{ 
    int i; 

    if (number < 0) number = -number; /* see Cthulhu's comment */ 

    while (number != 0) { 
     i = number % 10; 
     if (i == digit) return 1; 
     number = number/10; 
    } 
    return 0; 
} 

int main() 
{ 
    printf("3 in 12345: %d \n", is_digit_in_number(3, 12345)); 
    printf("9 in -12345: %d \n", is_digit_in_number(9, -12345)); 

    return 0; 
} 
+0

它不會爲第二個例子工作(雖然它會意外地報告正確的結果),因爲(如同它的愚蠢)'a%b' <= 0 for'a' <0在C++中 – Cthulhu

+0

已修復,謝謝!一些額外的字符來安撫Javascript並表達我的感激之情。 – MaxVT

0

您需要將您的號碼轉換爲字符串並搜索數字。

std::string str = std::to_string(ctemp); 
if(str.find_first_of('1')!=std::string::npos || 
    str.find_first_of('4')!=std::string::npos || 
    str.find_first_of('7')!=std::string::npos) 
{ 
    cout << "Found digits 1, 4, 7.\n"; 
} 
0

它是否包含1,4或7通過檢查的最後一位(1的位),您可以搜索一個整數,如果是1,4或7,並消除該數字檢查下一個。

#include <iostream> 
using namespace std; 

int main() 
{ 
    int a; 
    bool numberFound = false; 

    cout << "Enter a number: "; 
    cin >> a; 

    while (a != 0) 
    { 
     // determines if the last number is either 1, 4, or 7 
     switch (a % 10) 
     { 
     case 1: 
      cout << "1 is in the number." << endl; 
      numberFound = true; 
      break; 
     case 4: 
      cout << "4 is in the number." << endl; 
      numberFound = true; 
      break; 
     case 7: 
      cout << "7 is in the number." << endl; 
      numberFound = true; 
      break; 
     default: 
      numberFound = false; 
      break; 
     } 
     a /= 10; // removes the last digit so the next one can be checked 
    } 
    if (!numberFound) 
     cout << "1, 4, or 7 isn't in the number." << endl; 

    system("pause"); 
    return 0; 
}