2015-05-24 103 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; 
} 
相关问题