Trouble with while loop in for loop

Apr 19, 2017 at 12:49am
This function is to verify that the user input is the same as one of the array strings, but it keeps giving the "Not valid input" since it says its not the same as the one of the strings in the array. What am I doing wrong?

1
2
3
4
5
6
7
8
9
void r::valid(string& target){
  for (int i = 0; i < ROWS; i++) {
		while (target != a[i][0])
		{
			cout << "Not a valid input." << endl;
			cin >> target;
		}
	}
}
Last edited on Apr 19, 2017 at 12:52am
Apr 19, 2017 at 1:26am
target != a[i][0]
this matches the std::string target to the first element of a[i]. I suppose a is the array of strings? In that case you're comparing the std::string target to the first character of each of the a[i]'s.
Also your programme will print ROWS lines of output which might be superfluous if you just want a check whether or not target exists in a – an alternative way to do this might be:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include <string>
#include <algorithm>
#include <iterator>

int main()
{
   std::string a[] = {"hello", "world", "this", "is", "c++"};
   std::cout << "Enter target string \n";
   std::string target{};
   getline(std::cin, target);
   auto itr = std::find(std::begin(a), std::end(a), target);
   std::cout <<  ((itr != std::end(a)) ? "target found \n" : "not found \n");
}
Apr 19, 2017 at 1:38am
Would this also work if the array is 12 rows and 3 columns, because essentially I just want to check with all the values in one column and the then check by each row.
Apr 19, 2017 at 1:43am
is a a 2d array of strings? if so, or in general for 2d arrays, one way could be:
1
2
3
4
5
6
7
8
9
10
11
12
13
bool match = false;
for (size_t i = 0; i < ROWS; ++i)
{
    for (size_t j = 0; j < COLS; ++j)
    {
        if (target == a[i][j])
        {
            match = true;
            break;
        }
    }
}
if (match == true)std::cout << "Target found \n";
Last edited on Apr 19, 2017 at 1:48am
Apr 19, 2017 at 1:46am
Yes it's a 2d array of strings
Apr 19, 2017 at 1:49am
Yes it's a 2d array of strings

OK, see above then: http://www.cplusplus.com/forum/beginner/213581/#msg996314

in the OP you're only checking target against the first string in each row, not the others
Last edited on Apr 19, 2017 at 1:51am
Apr 19, 2017 at 1:57am
Ok so this verifies if it's true, but I also want it to repeat in case something is false so if what the user inputs is not in the array I would have the user input it again.How would I do that?
Apr 19, 2017 at 2:06am
you can just verify the value of match after the loops, so if match == false, not found
Apr 19, 2017 at 2:36am
Ok it worked thank you. I just have one more question how do I make it work for a c-string since I am dealing with both.
Apr 19, 2017 at 3:00am
Topic archived. No new replies allowed.