#include<iostream>
#include<vector>
#include<string>
using namespace std;
int contain(vector<string> &s_vector, string check)
{
cout<<"Input a string to check: ";
cin>>check;
if(s_vector=check)
return find(&s_vector);
else
return -1;
}
int main(){
vector<string>s_vector;
cout<<"Input the size of string vector: ";
int size;
cin>>size;
cout<<"Input "<<size<<"strings: \n";
cin>>s_vector[size];
cout<<"Strings in the string vector: ";
for(int i=0; i<s_vector.size(); i++)
cout<<s_vector[i]<<" ";
contain(s_vector, string check);
return 0;
}
I'm trying to make a code where you can find the index of a string. For example the output would be like:
Input the size of string vector: 3
Input 3 strings:
asd
lkj
qere
Input a string to check: lkj
1
But there seems to be some errors in the int contain~section, and if I take out the int contain~ section and run the program, it keeps saying "the run has stopped"whenever I try to input the strings. I'm new to C++ so I could really use your help thanks.
What your contain function might look like:
int contain(const vector<string>& s_vector)
{
cout << "Input a string to check: ";
string check;
cin >> check;
for (int i = 0; i < s_vector.size(); i++)
if (s_vector[i] == check)
return i;
return -1;
}
There's no need to pass the local variable check
to the function. We're comparing the strings inside the vector one by one by using operator []. main would look something like this:
int main()
{
vector<string>s_vector;
cout<<"Input the size of string vector: ";
int size;
cin>>size;
cout << "Input " << size << "strings: \n";
for (int i = 0; i < size; i++)
{
string str;
cin >> str;
s_vector.push_back(str);
}
cout<<"Strings in the string vector: ";
for(int i=0; i<s_vector.size(); i++)
cout<<s_vector[i]<<" ";
int i = contain(s_vector);
cout << "Index: " << i;
return 0;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.