The input file is opened in text mode, which means your program will never see the '\n' character(s) because getline() will filter it out, leaving only the characters up to but not including '\n'.
That read loop is wrong anyway because eof() doesn't work that way.
while (getline(infile, tmp)) {
str += tmp;
str += "\n";
}
I don't know what you mean by reading # 26. Does that file contain binary information? If yes, then it isn't a text file.
Ancient Dragon
Retired & Loving It
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343
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;
}
Ancient Dragon
Retired & Loving It
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343