Vector troubles?

So here's my code...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#include <iostream>
#include <vector>
#include <fstream>
#include <string>
#include <stdio.h>
#include <string.h>

using namespace std;







/*
while the file isn't done
store entire file into string
run a delimeter to take out spaces and store the end line as char in bhvFile

*/


int main(){
	vector<char> bhvFile;


	ifstream f ( "text.txt",std::ifstream::binary);
	int length = f.tellg();
	char * buffer = new char [length];
	f.open("Text.txt");
	f.read(buffer,length);
	/*IMPORTED FROM CPLUSPLUS.COM*/
	string str = buffer;
	char * cstr = new char [str.length()+1];
	std::strcpy (cstr, str.c_str());

  // cstr now contains a c-string copy of str

  char * p = std::strtok (cstr," ");
  /*END IMPORT*/
  while (p!=0)
  {
    std::cout << p << '\n';
    p = strtok(NULL," ");
  }
	
	while(p!=0){
		bhvFile.push_back(*p);
		p = strtok(NULL," ");
		
	}

	

	for(vector<char>::iterator i = bhvFile.begin();i !=bhvFile.end();++i){
		cout<<*i<<endl;

	}
	// To keep the cmd prompt from closing
	cin.ignore();
	return 0;
}






Basically I'm trying to figure out why my output is this,"=".

What I want it to do is output what the file contains to the vector and then push_back the character w/ a delimiter of," ".

Does that make sense? Sorry I'm bad at this.
Last edited on
closed account (DEUX92yv)
First off: using namespace std; means you don't have to put std:: in front of things. This namespace is already being used (courtesy of using namespace std;).

Second off: why do you want to store an end-of-file character?

Third off: I think this can be done without c-strings (in which case you don't need string.h)
Look into stringstream (personally I think this site's documentation on streams is poor - perhaps someone can suggest a good example?)
And, once you understand it, look up the std::string documentation here, especially operator>>

I believe that can do what you want it to, but I may have misunderstood your program.
Last edited on
1
2
3
	ifstream f ( "text.txt",std::ifstream::binary);
	int length = f.tellg();
	char * buffer = new char [length];


As you just opened the file and have read nothing from it, length will be 0, so you allocate a zero-length buffer and proceed to use it as if it were not. That results in undefined behavior on line 34 of the code in the OP. (And really? Copy a c-string to a C++ string and back to a c-string? What are you trying to accomplish there?)

Topic archived. No new replies allowed.