#include <iostream>
#include <vector>
#include <fstream>
#include <string>
#include <stdio.h>
#include <string.h>
usingnamespace 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 = newchar [length];
f.open("Text.txt");
f.read(buffer,length);
/*IMPORTED FROM CPLUSPLUS.COM*/
string str = buffer;
char * cstr = newchar [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," ".
First off: usingnamespace std; means you don't have to put std:: in front of things. This namespace is already being used (courtesy of usingnamespace 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.
ifstream f ( "text.txt",std::ifstream::binary);
int length = f.tellg();
char * buffer = newchar [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?)