Looking for a tutorial
| RDH37 (5) | |||
| Im looking for a tutorial on reading a txt file into a vector. If someone could give me a link or post an example here that would be great. | |||
| firedraco (657) | |||
| Look at: http://www.cplusplus.com/reference/iostream/fstream/ and http://www.cplusplus.com/reference/stl/vector/ Then you should be able to figure out how to do that. :) | |||
| RDH37 (5) | |||
| well this is what i have #include <iostream> #include <fstream> #include <string> #include <vector> using namespace std; int main() { string file; int size; vector <char> vector1; cout << "What file to open? "; cin >> file; ifstream x (file.c_str()); // get size of file x.seekg(0, ios::end); size = x.tellg(); x.seekg(0, ios::end); // allocate memory vector1.resize(size); // copy x into the vector x.read (&vector1.begin(), size); return 0; } but i get an error on the x.read line, what am i doing wrong? | |||
| Zhuge (102) | |||
| Please use code tags in your posts (# in the format area to the right of where you type your posts); it makes the code easier to read. Your problem with read is that vector does not work like that. Looking at the references firedraco provided, you can see that the first parameter needs to be of type
char* and
vector::begin() returns an
iterator to the beginning of the
vector. You will probably have to use a loop to get data into a temporary variable first then transfer it to the
vector until you are finished reading the file.Also, whenever you call
open(), you should check to ensure it succeeded and close the file when you are finished. In addition,
cin does not work with strings. Instead, use
getline(cin, file); | |||
| Duoas (1458) | |||||
A std::vector<char> is not as handy as a simple std::string. You can read an entire file into a string using a single getline():
Another useful option is a std::vector<std::string>
Hope this helps. | |||||
| RDH37 (5) | |||
Its been a couple days but I thought id post that i solved my problem myself,
x.read (&vector1.begin(), size); simply needed to be changed to
x.read (&(vector1[0]), size);. Thanks for the input anyway Duaos | |||
This topic is archived - New replies not allowed.
