Hi,
I'm really new to programming, so sorry if this is a silly question.
So I have an array of strings of indeterminate size, and the program is supposed to search through for a specific string and print out the line number where it was found. If it doesn't find the string it should print out an int. I am using a while loop to search through the program, but could I set the while condition to something else that will exit the loop upon reaching the end of the array? Or is there somehow a way to determine the size of the array (not in bytes)?
This is what I have so far: (the array is filled in main from a datafile)
int find (string search, string names [], int counter)
{
while ("TRUE")
{
if (names[counter] != search)
{
counter++;
}
if (names[counter] == search)
{
return counter;
}
}
}
You would have to pass in the size of your array, and compare counter to the array size. while (counter < size)
Are you always searching from the beginning of the array? If so, why are you passing in counter as an argument to your function?
I find it hard to believe that the size of the array is indeterminable.
How exactly is this array being populated with strings? You mentioned "line number", so I'm guessing you're reading strings from a file separated with a newline.
It shouldn't be too hard to keep track of the array size. Let us know how you're populating the array, and maybe we can suggest a better way of doing it (like STL containers, i.e. vector).
The array is populated by a datafile of 100 strings, using an ifstream. But I wanted to make it so I could put any size datafile and have it work. Yes it is reading in from strings separated with a newline.
I am always starting from the beginning. Does it matter whether it is in the argument or in the function? I thought you could do it both ways.
#include <iostream>
#include <vector>
#include <fstream>
#include <string>
void readStrings(std::vector<std::string>& strings, constchar* filename) {
std::ifstream stream(filename);
if(!stream) {return;}//If the file couldn't be loaded, handle this error somehow. Just returning is not safe.
std::string temp = "";
while(std::getline(stream, temp)) {
strings.push_back(temp);
temp.clear();
}
/*
Since strings are being pushed to the vector in the order they are read by line,
an index to an element in that vector will be analogous to a line in the file.
*/
}
unsignedlong searchStrings(const std::vector<std::string>& strings, const std::string& search) {
unsignedlong size = strings.size();
unsignedlong i = 0;
for(i=0; i<size; ++i) {
if(search==strings[i]) {break;}
}
return i;
}
int main(int argc, char* argv[]) {
if(argc!=2) {return 1;}
std::vector<std::string> strings;
readStrings(strings, argv[1]);
std::string search = "World";
unsignedlong index = searchStrings(strings, search);
std::cout << '\"' << search << '\"' << " found on line " << index << std::endl;
std::cin.get();
return 0;
}