loop and string length issues
Nov 17, 2015 at 9:03pm Nov 17, 2015 at 9:03pm UTC
Write your question here.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
#include <iostream>
#include <string>
#include <vector>
using std::cout;
using std::cin;
using std::endl;
using std::string;
using std::vector;
static bool truth = true ;
void looping(vector<string> plates, int numPlates);
int main(int argc, const char * argv[])
{
int numPlates;
string input;
cout << "How many plates are there? " ;
cin >> numPlates;
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n' );
vector<string> plates(numPlates);
for (int i = 0; i < numPlates; i++)
{
cout << "Enter plate " << i+1 << ": " ;
getline(cin, input);
plates[i] = input;
}
looping(plates, numPlates);
if (truth == false )
{
cout << "The door cannot be opened!" << endl;
}
else
{
cout << "The door can be opened!" << endl;
}
return 0;
}
void looping(vector<string> plates, int numPlates)
{
for (int i = 0; i < numPlates; i++)
{
for (int j = 0; j < numPlates; j++)
{
int last = plates[i].length() - 1;
cout << plates[i].length() << endl;
if (i == j)
{
// do nothing
}
else if (plates[i].at(last) == plates[j].at(0))
{
string temp = plates[i+1];
plates[i+1] = plates[j];
plates[j] = temp;
}
}
}
for (int i = 0; i < numPlates - 1; i++)
{
int last = plates[i].length() - 1;
//issues crop up
cout << plates[i].length() << endl;
/*
if (plates[i].at(last) != plates[i+1].at(0))
{
truth = false;
}
*/
}
}
This function tries to sort a bunch of different strings to see if you can match the first and last letter in a chain. Towards the end I seem to be having some issues with the .length function not working with the first plate[0] it seems to try to always say the length is 0. I can't see where it's getting changed to that length? I don't think I modify it anywhere. I'm also struggling with the loop to organize it. I think I could just make loop thats kind of a reverse of the first one I made to organize it in the other direction.
Nov 17, 2015 at 10:15pm Nov 17, 2015 at 10:15pm UTC
One thing is that you should make your vector a reference in the looping function:
1 2 3 4 5 6
void looping( vector< string >& plates, int numPlates )
{
...
}
Otherwise, you are calling by value and not changing the actual vector in main.
Topic archived. No new replies allowed.