2015-11-05 14 views
1

請問您會告訴我什麼是在所有字符串中查找字母表的過程(字符串列表)在C++中 輸出將只返回匹配的值(字母數字) 我嘗試這個程序檢查是否有任何字母表(az)存在於所有字符串(小說列表)中並且打印發現的字母數量

 #include <vector> 
#include <iostream> 
#include <cstdio> 

int main() 
{ 
    //setup 
    std::vector<int> alphabetCount; 

    for (int i = 0; i < 26; ++i) 
    { 
     alphabetCount.push_back(0); 
    } 

    //now the interactive bit 
    std::cout << "Enter a line of text\n"; 
    std::string line; 
    std::getline(std::cin, line); 

    for (size_t i = 0; i < line.size(); ++i) 
    { 
     char currentChar = tolower(line[i]); 
     if (isalpha(currentChar)) 
     { 
      ++alphabetCount[currentChar - 'a']; //subtract a, so if currentChar = a, 'a' - 'a' = 0, so its index 0 
     } 
    } 

    for (size_t i = 0; i < alphabetCount.size(); ++i) 
    { 
     std::cout << "there were " << alphabetCount[i] << " occurences of " << static_cast<char>(i + 'a') << "\n"; //add 'a' for the same reason as above, though we have to cast it to a char. 
    } 
system("pause"); 
    return 0; 
} 

但只返回一個字符串,我想爲什麼它正在一個從所有的字符串

+0

題外話:'的std ::矢量 alphabetCount(26);'將與26個零預加載向量和替換第一個for循環。 – user4581301

回答

0

原因導致值一次一個字符串是因爲你正在輸入一個字符串,你應該創建一個字符串的向量並接受輸入在裏面。

+0

你是否請示範? 我是新的我不明白 –

0

您在程序中沒有多次讀取該字符串。下面是示例程序,這是非常天真的演示過程。循環終止條件可以比我的好得多。

int main() 
 
{ 
 
    //setup 
 
    std::vector<int> alphabetCount; 
 

 
    for (int i = 0; i < 26; ++i) 
 
    { 
 
     alphabetCount.push_back(0); 
 
    } 
 

 
    //now the interactive bit 
 
    std::cout << "Enter a line of text\n"; 
 
    std::string line; 
 
\t do{ 
 
\t \t std::getline(std::cin, line); 
 
\t \t for (size_t i = 0; i < line.size(); ++i) 
 
\t \t { 
 
\t \t \t char currentChar = tolower(line[i]); 
 
\t \t \t if (isalpha(currentChar)) 
 
\t \t \t { 
 
\t \t \t \t ++alphabetCount[currentChar - 'a']; //subtract a, so if currentChar = a, 'a' - 'a' = 0, so its index 0 
 
\t \t \t } 
 
\t \t } 
 
\t }while(line != "exit"); 
 

 
\t --alphabetCount['e' - 'a']; 
 
\t --alphabetCount['x' - 'a']; 
 
\t --alphabetCount['i' - 'a']; 
 
\t --alphabetCount['t' - 'a']; 
 

 
    for (size_t i = 0; i < alphabetCount.size(); ++i) 
 
    { 
 
     std::cout << "there were " << alphabetCount[i] << " occurences of " << static_cast<char>(i + 'a') << "\n"; //add 'a' for the same reason as above, though we have to cast it to a char. 
 
    } 
 
\t system("pause"); 
 
    return 0; 
 
}

+0

建議使用空字符串,而不是「退出」的終止符。更容易打字和清理。 – user4581301

相關問題