Loop within IF statement condition - c++

i just want to know if there is a way for a loop to be on the If statement condition?
sample:
if((string.contains(stringlist.hello().value(0),Qt::CaseInsensitive))||(string.contains(stringlist.hello().value(1),Qt::CaseInsensitive))||(string.contains(stringlist.hello().value(2),Qt::CaseInsensitive)))
{
...
}
to be:
if
(
for(int i=0; i < stringlist.hello().size(); i++)
{
string.contains(stringlist.hello().value(i),Qt::CaseInsensitive)
}
)
{
...
}
by the way hello() function retrieves list of data from the database.
the purpose of this program is to check a string if it contains some keywords from the database.

That code will not compile; instead, you might try a solution that checks each condition and stores the result into a variable determining whether or not the condition is met:
bool testCond = false;
for(int i=0; i < stringlist.hello().size(); i++)
{
if (string.contains(stringlist.hello().value(i),Qt::CaseInsensitive))
{
testCond = true;
break;
}
}
if (testCond)
{
// code here if any of the conditions in the for loop are true
}
I changed my code to use bool instead of int's, as it looks like you are using C++.

Related

How to find a certain value in a vector of strings

I'm trying to create a program for an assignment that will add and remove strings from a vector of strings, but first I need to create a function that will find whether or not the string already exists in the vector.
I've already tried to use a loop to search through the vector to find a specific desired string at each index. I tried adding a break; to exit if the string was found. I don't know if the function is supposed to be void or boolean.
bool FindString(int vctrSize, vector<string> restaurantVctr, string targetRestnt) {
int i;
for (i = 0; i < vctrSize; ++i) {
if (restaurantVctr.at(i) == targetRestnt) {
return true;
break;
}
else {
return false;
}
}
}
I expect the output to be true if the string was found, else it would obviously be false.
Edit: I forgot to mention that I also received the warning: "not all control paths return a value"
You should use std algorithms whenever possible:
auto result = std::find(restaurantVctr.begin(), restaurantVctr.end(), targetRestnt);
return result != restaurantVctr.end();
That is exactly what std::find is for.
While I recommend using std::find as others have recommended, if you're curious what is wrong with your code, the problem is your else:
for (i = 0; i < vctrSize; ++i) {
if (restaurantVctr.at(i) == targetRestnt) {
return true;
break;
}
else {
return false;
}
}
If the first item in your vector is not equal to targetRestnt, then your function returns--that is, it ends execution.
You only want to return false if it's not in the whole list--that is, you want the whole loop to execute:
for (i = 0; i < vctrSize; ++i) {
if (restaurantVctr.at(i) == targetRestnt) {
return true;
// Also, you don't need a break here: you can remove it completely
// For now, I just commented it out
// break;
}
}
// We didn't find it:
return false;

Function checking values of type chars

I am new to programming and have an exercise in which I create a function to check whether an array of type char hold particular values.
Here is my function:
bool arrCheck(char n[],char pos1,char pos2,char pos3,int size)
{
int n1,n2,n3;
for (int i=0;i<size;i++)
{
if (n[i]==pos1)
{
n1=1;
}
if (n[i]==pos2)
{
n2=1;
}
if (n[i]==pos3)
{
n3=1;
}
}
if ((n1==1)&&(n2==1)&&(n3==1))
{
return true;
}
}
here is my test program:
int main()
{
char a[5]={'6','1','a','a','a'};
if (arrCheck(a,'1','6','9',5))
{
cout<<"true\n";
}
}
I thought the result is supposed to be false but all I got is true. What did I do wrong?
n1, n2 and n3 are default-initialized and they have indeterminate values at first. Initialize them before checking their values. Also do not forget to return something even when the condition is false.
Try this:
bool arrCheck(char n[],char pos1,char pos2,char pos3,int size)
{
int n1=0,n2=0,n3=0;
for (int i=0;i<size;i++)
{
if (n[i]==pos1)
{
n1=1;
}
if (n[i]==pos2)
{
n2=1;
}
if (n[i]==pos3)
{
n3=1;
}
}
return (n1==1)&&(n2==1)&&(n3==1);
}
Using boolto store boolean values and using const to mark that the contents of array won't be changed may be better .
bool arrCheck(const char n[],char pos1,char pos2,char pos3,int size)
{
bool n1=false,n2=false,n3=false;
for (int i=0;i<size;i++)
{
n1=n1||(n[i]==pos1);
n2=n2||(n[i]==pos2);
n3=n3||(n[i]==pos3);
}
return n1&&n2&&n3;
}
1) Use a bool variable instead of three int variable
2) Initialize it (You have not initialized the int variable and they have random garbage value)
3) Also add else condition to return false value (Your code is not returning false).
4)Also print false in main function using else condition.
Hope this helps you..!
THE CODE IS ALRIGHT. You just forgot to add some statements and this is causing the error (it might or might not have been silly on your part).
Your definition of the function arrCheck() is incomplete. It returns true if a certain condition is fulfilled but what if it isn't? In that case, you must return false. But in your code, false is never returned. So firstly, you've gotta add an else statement after the last if statement in the arrCheck() method to this:
if((n1==1)&&(n2==1)&&(n3==1)){
return true;
}
else{
return false; //this has to be added
}
It can now return false if such a case is encountered.
Also, you must display "false" in the main method if arrCheck() returns false. You are recommended to add an else statement after the if statement in the main() method. See the modification below:
if (arrCheck(a,'1','6','9',5))
{
cout<<"true\n";
}
else{
cout<<"false\n"; //it must show false;
}
Once you correct these, your code will produce the correct output.
P.S. This answer serves as an elaboration of the answer earlier submitted by #KUSHAGRA GUPTA.
int n1,n2,n3;
This line leads to undefined behaviour because you do not initialise the variables yet attempt to read from them later on even if not all of them have been assigned a value:
if ((n1==1)&&(n2==1)&&(n3==1))
Fix the undefined behaviour by initialising the variables to 0:
int n1 = 0;
int n2 = 0;
int n3 = 0;
There is another case of undefined behaviour when your function does not state what to return if the condition is not true. Fix this, too:
if ((n1==1)&&(n2==1)&&(n3==1))
{
return true;
}
else
{
return false;
}
Or simply:
return (n1==1)&&(n2==1)&&(n3==1);
change that line to like this.int n1= 0,n2= 0,n3 = 0;
because when uninitialized these variable have garbage values.
bool arrCheck(char n[],char pos1,char pos2,char pos3,int size)
{
int first = 0,second = 0, third = 0;
for (int i=0;i<size;i++) {
if (n[i]==pos1) {
first = 1;
} else if (n[i]==pos2) {
second = 1;
} else if (n[i]==pos3) {
third = 1;
}
}
if( first+ second + third == 3)
return true;
else
return false;
}

Error: not all control paths return a value

I am writing two functions in a program to check if a string has an assigned numeric code to its structure array or if the given numeric code has an assigned string in the same structure array. Basically, if I only know one of the two, I can get the other. I wrote the following:
int PrimaryIndex::check_title_pos(std::string title) {
bool findPos = true;
if (findPos) {
for (int s = 1; s <= 25; s++) {
if (my_list[s].title == title) {
return s;
}
}
} else {
return -1;
}
}
std::string PrimaryIndex::check_title_at_pos(int pos) {
bool findTitle = true;
if (findTitle) {
for (int p = 1; p <= 25; p++) {
if (my_list[p].tag == pos) {
return my_list[p].title;
}
}
} else {
return "No title retrievable from " + pos;
}
}
However, it says not all control paths have a return value. I thought the else {} statement would handle that but it's not. Likewise, I added default "return -1;" and "return "";" to the appropriate functions handling int and string, respectively. That just caused it to error out.
Any idea on how I can keep this code, as I'd like to think it works but cant test it, while giving my compiler happiness? I realize through other searches that it sees conditions that could otherwise end in no returning values but theoretically, if I am right, it should work fine. :|
Thanks
In the below snippet, if s iterates to 26 without the inner if ever evaluating to true then a return statement is never reached.
if (findPos) {
for (int s = 1; s <= 25; s++) {
if (my_list[s].title == title) {
return s;
}
}
}

Searching first specified element in array

I'm trying to make function that has a loop that checks every member of an array made from boolean variables and exits when it finds the first "true" value.
That's what I have now:
bool solids[50];
int a,i;
//"equality" is a function that checks the equality between "a" and a defined value
solids[0] = equality(a,&value_1);
solids[1] = equality(a,&value_1);
solids[2] = equality(a,&value_1);
solids[3] = equality(a,&value_1);
for (i = 0; solids[i] != true; i++)
{
[...]
}
But I have no idea, what should I put into the loop?
My attempt was
for (i = 0; i <= 50; i++)
{
if (solids[i] == true)
{
return true;
break;
} else {
return false;
}
}
,that should return true after the first found true and return false if the array has no member with true value, but it doesn't seem to work in the code.
Is it wrong? If yes, what is the problem?
PS.: I may count the number of trues with a counter but that's not an optimal solve to the problem, since I just look for the FIRST true value and consequently, the program doesn't have to check all the 50 members. Needley to count, how many unnecesary steps should this solve would mean.
here's a short example usage of std::find() as advised by #chris:
bool find_element_in_array() {
bool solids[50];
int length;
/* ... do many operations, and keep length as the size of values inserted in solids */
bool* location = std::find(solids, length, true);
// if element is found return true
if (location != solids + length)
return true;
// else return false
return false;
}
Once you have solids correctly set (it looks like you're currently setting every value to the same thing), you can make a loop that exits on the first true like this:
for (i = 0; i < 50; i++)
{
if (solids[i] == true)
{
return true;
}
}
return false;
I'd also just move the declaration of i into the for loop body, since it's not used outside, but the above answers your question.
return immediately exits the function, so there is no need to break the loop after.
If it's sufficient to exit the function right after the search, you should write something like:
for (int i = 0; i < 50; i++) {
if (solids[i]) return true;
}
return false;
If you need to use the result of the search in the same function, use additional variable:
bool found = false;
for (int = 0; i < 50; i++) {
if (solids[i]) {
bool = true;
break;
}
}
if (found) { ...

Indexing my while loop with count parameter in an array

My function takes an array of ifstream ofjects and the number of ifstream objects as seen below:
void MergeAndDisplay(ifstream files[], size_t count)
My problem is I want to use a while loop to read from the file(s) as long as one of them is open. When I get to eof, I close the file. So I thought I could do something like
int fileNum = 0;
while(files[fileNum].is_open() || something here) {
//do stuff
}
But I am not really sure how to put the correct amount of parameters in my while loop...
You will have to compute the logic of "is any file in this set open" separately. I suggest making it its own function so that the while loop can be clean and natural, e.g.
bool isAnyOpen(ifstream files[], size_t count) {
for (size_t i = 0; i < count; ++i) {
if (files[i].is_open()) return true;
}
return false;
}
Then you can write
while(isAnyOpen(files, count)) {
// Your code here
}
Edit: This is a more general case solution than what R Samuel Klatchko posted. If your problem is as simple as wanting to just read all the data out of all the files, then use his method since it is more direct.
You probably want
while (fileNum < count && files[fileNum].is_open())
with the condition that you increment fileNum whenever you open a new file in your loop.
Try something like this:
void ProcessStream(std::istream& input_file)
{
//...
}
// Your loop
bool a_file_is_open = true;
do
{
a_file_is_open = false;
for (unsigned int i = 0; i < MAX_FILES; ++i)
{
if (files[i].is_open())
{
a_file_is_open = true;
ProcessStream(files[i]);
break;
}
}
} while (a_file_is_open);