why am i getting a segmentation fault in c++ when i am just copying vectors?
This is really weird. If you look at the bolded line, that is the one causing the segmentation fault. What I am trying to do in this program is take in a text file with about 100 lines of text and separate them into words. I need to get a vector with all the words in them so I can then count how many of each word appears....any help is appreciated. Thanks!!!!!
#include <fstream> / #include <sstream> #include <string> #include <iomanip> #include <cstring> #include <iostream> #include <vector> using namespace std; int main(int argc, char* argv[]) { ifstream datafile; char filename[80]; cout << "Enter file: "; cin >> filename; string line; datafile.open(filename); if (datafile.is_open()); { while (! datafile.eof()) { vector<string> tokens; getline (datafile, line); vector<string> returned_strings; char* current_token =strtok(const_cast<char*>(line.c_str()), " "); while (current_token != NULL) { returned_strings.push_back(string(current_token)); current_token = strtok(NULL, " "); } for (int i = 0; i < returned_strings.size(); ++i) { cout << returned_strings[i] << endl; tokens[i]=returned_strings[i]; } } datafile.close(); } return 0; } |
why not use the old fashion char *
|
Quote:
tokens[i] is only valid if the vector is already big enough that element i exists. If the vector is not big enough, that usage does not extend the vector, it seg faults (as you have observed). |
Hello.
1. Code:
vector<string> tokens; 2. Why not use tokens = returned_strings ? 3. tokens is not used until -after- returned_strings is "filled", and the two vectors appear to have the same scope. Why not postpone the definition and then use a copy constructor? 4. Here is something hastily adapted from some code pieces present in "The C++ Programming Language - 3rd edition" [Bjarne Stroustrup]: Code:
#include <algorithm> |
All times are GMT -5. The time now is 12:47 PM. |