将字符串数组放入参数中,然后将元素与字面值字符串进行比较

Putting String array in parameter, then comparing the elements to literal strings error?

本文关键字:字符串 字面值 比较 元素 数组 参数 然后      更新时间:2023-10-16

假设我有一个数组

string test = {"test1, "test2"}

我有函数

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

但是当我编译这个时,我得到一个错误…为什么呢?有不同的方法吗?

您的测试变量应该声明为数组类型

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

您还需要从

更改函数签名
void testing(string test)

void testing(string* test){

你写的代码不会编译,因为错误的字符串数组声明。替换

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;
}