2015-05-24 121 views
-1

比方說,我有一個數組將字符串數組放入參數中,然後將元素與文字字符串錯誤進行比較?

string test = {"test1, "test2"} 

我有我的功能

void testing(string test){ 
    for(int i = 0; i < 2; i++){ 
    if(test[i] == "test1"){ 
     cout << "success" << endl; 
    } 
    } 
} 

但是,當我編譯此,我得到一個錯誤......這是爲什麼? 有沒有不同的方法?

+0

'字符串測試'看起來不像一個數組。它看起來像'string'。 – juanchopanza

+0

'string test'中缺少''''test1'。 – shruti1810

回答

2

您的測試變量應被聲明爲數組類型

string test[] = {"test1", "test2"}; 

您還需要函數簽名從

void testing(string test) 

改變

void testing(string* test){ 
0

你寫的代碼是由於字符串數組的錯誤聲明而不會編譯。 更換

string test = {"test1, "test2"}; 

string test[]={"test1, "test2"}; 

下面的代碼使用數組中的位置,而不功能

#include <iostream> 
#include <string> 

using namespace std; 

string test[]={"test1, "test2"}; 
for(auto& item:test) 
{ 
    cout<<item<<endl; 
} 

我認爲得到這個與功能之一是使用矢量

的最佳方式
#include <iostream> 
#include <string> 
#include <vector> 
using namespace std; 

void testing(const vector<string>& strings) 
{ 
    for (auto& item : strings) 
    { 
     cout << item << endl; 
    } 
} 
int _tmain(int argc, _TCHAR* argv[]) 
{ 
    vector<string> strings = { "str1", "str2", "str3" }; 
    testing(strings); 
    cin.get(); 
    return 0; 
} 
相關問題