Click to See Complete Forum and Search --> : Arrays


raz0rblade
06-09-2003, 02:53 AM
I did a search on google, but I couldnt understand it. What im trying to do is put every line of a file into an array, each line gets an array space. My code:


int parse(const std::string& x){

std::string x;
std::string array[500]
std::ifstream ifs(x);
while (!ifs.eof()) {
x=array[[1]..[500]]


}
Im just guessing, but I hope somebody understands what im trying to do. Also how can i make the array the exact size as the lines in the file. It will be changing all the time, how could I do this other than making a huge array ?

tecknophreak
06-09-2003, 08:33 AM
You could use a c-string(array of chars), fill it with ifs.getline(), then copy that into a std::string.

Stuka
06-09-2003, 09:46 AM
Don't use an array - use a std::vector<std::string>. It will resize itself automatically to fit the size of your input.int parse(const std::string& x){

std::string temp;
std::vector<std::string> array;
std::ifstream ifs(x);
while (!ifs.eof()) {
std::getline(ifs, temp);
array.push_back(temp);
}
}

tecknophreak
06-09-2003, 10:34 AM
You can use a string with getline? Well, I guess you learn something new everyday. I also learned that I should find some new C++ references while at work, or bring in some from home.

raz0rblade
06-09-2003, 05:43 PM
Thnx Stuka, I can access each line through array[#] right ?

RHLinuxNewbie
06-09-2003, 06:17 PM
I wrote a small program in c++ to change my fluxbox menu when I mount/unmount specific partitions. This is a function I used.. you might want to use it, or just learn from it, either way, hope it helps.



vector<string> CasheFile(string file) {
ifstream cFile(file.c_str());

vector<string> Cashe;
if (cFile.fail()) {
cout << "ERROR: " << file << " could not be opened.\n";

exit(1);
} else {

string line;

while (getline(cFile, line)) {
Cashe.resize(Cashe.size() + 1);
Cashe[Cashe.size() - 1] = line;
}

}
cFile.close();
return Cashe;
}



You'll need the following headers:
string
vector

fstream

Stuka
06-10-2003, 10:59 AM
raz0rblade: yes, you can. However, for true STL-ness, if you're doing line by line processing, you should use a std::vector<std::string>::iterator to go through the array. However, vectors do offer random access, so you can access them like arrays.