将字符串数组放入参数中,然后将元素与字面值字符串进行比较
Putting String array in parameter, then comparing the elements to literal strings error?
假设我有一个数组
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;
}
相关文章:
- 为什么添加两个字符串字面值不使用操作符+
- c++的字符串字面值如何存储在内存中?
- 为什么可以向字符串字面值添加整数?
- 可修改字符串字面值的用例
- c++ constexpr vs宏,字符串字面值vs整数
- 字符串对字符串字面值的优化不够
- 是否有可能合法地重载字符串字面值和const char*
- UnicodeString /字符串字面值vs十六进制值
- 为什么将指针的内容修改为字符串字面值是错误的?
- c++: Std::cout缓冲区错误?对字符串变量和字符串字面值使用std::cout导致输出混乱
- C/ c++预处理器中的宏参数字符串化为宽字符串字面值
- 试图对初始化为字符串字面值的char指针的未定义行为进行推理
- 如何从字符串字面值初始化无符号字符数组
- 为什么空字符串字面值被视为真?
- 将字符串字面值的第一个字符赋值给字符数组将赋值整个字符串字面值
- 将传递的参数限制为字符串字面值
- 使用c风格字符串字面值与构造未命名std::string对象的默认建议
- 为什么我可以将字符串字面值赋值给char*指针
- 字符串字面值操作-复制字符
- 强制' const char[] '字符串字面值