test.txt is a binary file, not a text file so getline() doesn't know how to read it. Then you are putting all that binary stuff into a std::string and ucing cout to display it -- cout can't because it doesn't know how to display binary data when converted to char.
Use a hex editor on that test.txt file and it contains the 4 values that were written.
Maybe this is what you want?
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <sstream>
using namespace std;
int main()
{
// fill up the vector with 4 integers
vector <int> vec;
vec.push_back(21);
vec.push_back(23);
vec.push_back(26);
vec.push_back(29);
cout << "Numbers in vector are:" << endl;
for (size_t i = 0; i < vec.size(); i++) {
cout << vec[i] << " ";
}
//write out the vector contents as chars to a text file
ofstream outfile("test.txt");
if (outfile.fail()) {
cout << "test.txt"
<< endl;
return 1;
}
for (size_t g = 0; g < vec.size(); g++) {
outfile << char(vec[g]);
}
outfile.close();
vec.erase(vec.begin(),vec.end());
//now read the chars back in as the ints [21, 23, 26, 29]
ifstream infile("test.txt", ios::binary);
if (infile.fail()) {
cout << "Error opening test.txt"
<< endl;
return 1;
}
char c;
std::string str;
while (infile.good()) {
c = infile.get();
std::stringstream sstm;
sstm << c;
str += sstm.str();
}
infile.close();
cout << endl << "String read in is:" <<endl;
for (size_t g=0; g<str.size(); g++) {
cout << int(str[g]) << " ";
}
cout << endl;
}
Sponsor
Team Colleague
Featured Poster
Reputation Points: 5608
Solved Threads: 2282
Retired and Enjoying Life
Offline 21,951 posts
since Aug 2005