2016-12-14 79 views
0

作爲一項家庭作業練習,我們被要求使用strchr來計算單個字母出現在一串文本中的次數。它需要計數大小寫均等。有人建議我們使用某種比特操作。 我設法得到一個工作程序。如何使用cin獲取字符串而不是硬編碼?

但我想通過允許我使用cin輸入字符串而不是直接在源代碼中輸入字符串(這是練習要求的)來使程序更具交互性。 可以做到這一點嗎?或者,這是不可能的,我寫這個代碼的方式。

#include <iostream> 
#include <cstring> 
using namespace std; 
int main(){ 
    const char *C = "This is a necesarry test, needed for testing."; 
    char target = 'A'; 
    const char *result = C; 
    const char *result2; 
    int count = 0; 
    int j[26] ={0}; 
//================================================================================================================================================ 
    for(int i = 0; i <= 51; i++){ 
     if (i == 26){ 
      target = target + 6; 
     } 
     result2 = strchr(result, target); 

     while(result2 != NULL){ 
      if (result2 != NULL){ 
       result2 = strchr(result2+1, target); 

       if (i <= 25){ 
        j[i] = j[i] +1; 
       } 
       if(i > 25){ 
        j[i-26] = j[i-26] +1; 
       } 
       cout << target << "\t"; 
      } 


    } 

    cout << target << endl; 
    target++; 

    } 

    char top = 'a'; 
    for(int o = 0; o<= 25; o++){ 
     cout << "________________________________\n"; 
     cout << "|\t" << top << "\t|\t" << j[o] << "\t|" << endl; 
     top++; 
    } 
    cout << "________________________________\n"; 

    } 
+2

看看['標準:: getline'(HTTP:// WWW。 cplusplus.com/reference/string/string/getline/) – qxz

回答

1

只需使用getline()從控制檯獲取字符串即可。使用getline你也可以考慮用戶輸入中的空格。

string input; 
getline(cin, input); 

我們利用此功能,和strchr功能N您只需將其轉換成可以做一個C類型的字符串如下:

input.c_str 

這將返回一個C型字符串,所以你可以把以此爲arguement的功能,

您需要

#include <string> 
相關問題