Writing a C++ vector to an output file - c++

ofstream outputFile ("output.txt");
if (outputFile.is_open())
{
outputFile << "GLfloat vector[]={" << copy(vector.begin(), vector.end(), ostream_iterator<float>(cout, ", ")); << "}" << endl;
}
else cout << "Unable to open output file";
How do I output a vector to a file, with each float separated by commas? I would also like to avoid printing square brackets if possible.

outputFile << "GLfloat vector[]={";
copy(vector.begin(), vector.end(), ostream_iterator<float>(outputFile , ", "));
^^^^^^^^^^
outputFile << "}" << endl;

First, you shouldn't call your variable vector. Give it a name which is not the name of a class from the Standard Library.
Secondly, ostream_iterator will append a ',' even after the last element of the vector, which may not be what you want (a separator should be a separator, and there's nothing to separate the last value of the vector from a further value).
In C++11, you could use a simple range-based for loop:
outputFile << "GLfloat vector[]={";
auto first = true;
for (float f : v)
{
if (!first) { outputFile << ","; }
first = false;
outputFile << f;
}
outputFile << "}" << endl;
In C++03, it is going to be just a bit more verbose:
outputFile << "GLfloat vector[]={";
auto first = true;
for (vector<float>::iterator i = v.begin(); i != end(); ++i)
{
if (!first) { outputFile << ","; c++; }
first = false;
outputFile << *i;
}
outputFile << "}" << endl;

You've taken the solution and attempted to stick it into the stream insertion. That's not how it works. It should be a separate line:
outputFile << "GLfloat vector[]={";
copy(vector.begin(), vector.end(), ostream_iterator<float>(outputFile, ", "));
outputFile << "}" << endl;
The copy algorithm simply copies elements from one range to another. ostream_iterator is a special iterator that will actually insert (with <<) into the given stream when you do *it = item_to_insert;.

Here is a nice generic (header-only) library, which you just need to include in your code and it will allow you to print any standard containers easily: http://louisdx.github.com/cxx-prettyprint/

Related

Reading in fasta file C++

I'm trying to read in a fasta file. I want to remove/ignore the header/info lines that begin with ">" and store the following sequences into sperate strings. Below is the code I have to do that (partially reworked from https://rosettacode.org/wiki/FASTA_format#C++, as what I had originally worked even less). They have a good example of what I want to do.
My problem is given this fasta file:
">sequence_1
MSTAGKVIKCKAAVLWELHKPFTIEDIEVAPPKAHEVRIKMVATGVCRSDDHVVSGTLVTPLPAVLGHE
GAGIVEG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APPKAYEVRIKMVAVGICHTDDHVVSGNLVTPLPVILGHEAAGIVESVGEGVTTVKPGDKVIPLFTCRVCKNPESNYCLKNDLGNPRGTLQDGTRRFTCRGKPIHHFLGTSTFSQYTVVDENAVAKIDAASPLEKVCLIGCGFSTGYGSAVNVAKVTPGSTCAVFGLGGVGLSAVMGCKAAGAARIIAVDINKDKFAKAKELGATECINPQDYKLPIQEVLKEMTDGSTVIGRLDTMMASLLCCGTSVIVEDTPASQNLSINPMLLLTGRTWKGAVYGGFKSKEGIPKLVADFMAKKFSLDALITHVLPFEKINEGF
The last line or so of Sequence 2 is cut off..... Any help/solutions?
void read_in_Protein(string Protein_filename)
{ // read in the sequences
fstream myfile;
myfile.open(Protein_filename, ios::in);
if (!myfile.is_open()) {
cerr << "Error can not open file" << endl;
exit(1);
}
string Protein_Sequences{};
string Protein_Seq_names{};
// string temp{};
string Prot_Seq1{};
string Prot_Seq2{};
string line{};
while (getline(myfile, line).good()) {
//std::cout << "Line input received (" << line.length() << "): " << line << std::endl;
if (line.empty() || line[0] == '>') { // Identifier marker
if (!Protein_Seq_names.empty()) { // Print out what we read from the last entry
//std::cout << "\tReseting to new sequence" << std::endl;
// cout << Protein_Sequences << endl;
Protein_Seq_names.clear();
Prot_Seq1 = Protein_Sequences;
}
if (!line.empty()) {
//std::cout << "\tSetting sequence start" << std::endl;
Protein_Seq_names = line.substr(1);
}
// std::cout << "\tClearing sequences..." << std::endl;
Protein_Sequences.clear();
}
else if (!Protein_Seq_names.empty()) {
line = line.substr(0, line.length() - 1);
if (line.find(' ') != string::npos) { // Invalid sequence--no spaces allowed
//std::cout << "\tSpace found, clearing buffers..." << std::endl;
Protein_Seq_names.clear();
Protein_Sequences.clear();
}
else {
//std::cout << "\tAppending line to protein sequence..." << std::endl;
Protein_Sequences += line;
}
}
//std::cout << "Protein_Sequences: " << Protein_Sequences << std::endl;
}
if (!Protein_Seq_names.empty()) { // Print out what we read from the last entry
// cout << Protein_Sequences << endl;
Prot_Seq2 = Protein_Sequences;
}
cout << "\nSequence 1: " << Prot_Seq1 << endl;
cout << Prot_Seq1.length();
cout << "\nSequence 2: " << Prot_Seq2 << endl;
cout << Prot_Seq2.length();
}
Assuming your file doesn't end with a new line then the last call to std::getline will set the eof bit to indicate that it reached the end of the file before finding the line ending. As you are checking .good() in your while loop the last line will be discarded. You should instead check !fail() (or just the boolean value of the stream itself which is equivalent to !fail()):
while (getline(myfile, line))
After reading the final line the next iteration of the loop will try to read whilst the stream is in the eof state and immediately fail and break out of the loop.

Confused about behavior when reading stdin c++

I am attempting to solve a problem to improve my C++ skills. I have come across some unusual behavior and I am not sure why it is happening.
I initially parsed the stdin and sorted it into a map with a key and a matching element (value). I then want to read a list of keys and output the element (value). However, for some of the key names it returns the correct value but for others it does not, but, if I hard code the intended key it works.
I know I am parsing correctly since the correct key and value are in the map as shown at the end of my output.
I assume it is an issue with reading stdin since the boolean str.compare("tag1.tag2~name") == 0 never evaluates to 0.
The code is as follows:
//'it' is the name of my map
//q = 3
for (int i = 0; i < q; i++)
{
getline(cin, str);
if (str.compare("tag1.tag2~name") == 0)
{
cout << "key is found" << endl;
}
else
{
cout << "'" << str << "'" << endl;
}
if (it.count(str) == 0)
{
cout << "Not Found!" << endl;
}
else
{
cout << it[str] << endl;
}
}
map<string, string>::iterator ptr;
cout << "\nThe map it is : \n";
cout << "\tKEY\tELEMENT\n";
for (ptr = it.begin(); ptr != it.end(); ++ptr) {
cout << '\t' << ptr->first
<<"\t" + ptr->second << "\n";
}
return 0;
The output is:
'tag1.tag2~name
Not Found!
'tag1~name
Not Found!
'tag1~value'
HelloWorld
The map it is :
KEY ELEMENT
tag1.tag2~name Name1
tag1~value HelloWorld
The input is :
tag1.tag2~name
tag1~name
tag1~value
Thank you! I have been struggling with this for a while.

fstream << operate not writing entire output

Everthing goes well until the f << "string" << temp_int << endl; statement
get different results with different openmodes, either doesn't write at all or writes the first two chars of "NumberSaves"
unsigned int temp_int = 0;
fstream f("resources/saveData/Player/savelog.txt");
if (!f)
{
cout << "error accessing savelist" << endl;
}
else
{
string skip;
std::stringstream iss;
string line;
readVarFromFile(f, iss, skip, line, { &temp_int }); //check how many saves currently
temp_int += 1; //increment number of saves by 1
f.seekp(ios_base::beg);
cout << "Write position: " << f.tellp() << endl; //check stream is at beginning
f << "<NumberSaves>" << temp_int << endl; //truncate <NumberSaves> 'x' with <NumberSaves> 'x + 1'
cout << "Write position: " << f.tellp() << endl; //position suggests the entire string has been written, only two characters have been
if (!f)
{
cout << "ERROR";
}
f.seekp(ios_base::end);
f << currentPlayer->getName(); //append players name to end of file
}
desired output is as follows
NumberSaves 2
player
anotherplayer
current output
Nu
player
Use seekp properly like this:
os.seekp(0, std::ios_base::end); // means bring me to 0 from the end of file.
look at the example code in
http://en.cppreference.com/w/cpp/io/basic_ostream/seekp
std::ios_base::end is a direction not an absolute position. It is just an enum value. The value is probably 2 and that is why it brings you to position 2 inside the file.

Using std::next() in Netbeans

I've been writing an XML to JSON converter in C++ in Visual Studio 2012 and I've used std::next() a bunch in my program. Our professor wants us to be using Netbeans to submit out programs, but I went to bring my code over into Netbeans and now everywhere I've been using std::next is now underlined and my code wont compile. Here is an example of where I'm encountering an error. Does anyone know a workaround? Thanks in advance.
void element::printAttributesToFile(ofstream& outFile)
{
map<string, string>::iterator it; //for iterating through the map of attributes and values
if(attributes.size()>1) //if there are more than one attribute, make an array
{
outFile << "[" << endl;
}
for(it=attributes.begin(); it != attributes.end(); ++it) // iterates through the map
{
outFile << "{" << endl; //brackets surrounding ever attribute
outFile<<"\""<<it->first<<"\": "<< "\""<< it->second<<","<<endl;
if(!content.empty()){ // if there is content, print it
outFile<<"\"content\": "<< "\""<< content << "\"" <<endl;
}
outFile << "}" << endl;
if(next(it) != attributes.end()) //is this the last attribute
{
outFile << "," << endl; //if not, print the comma
}else if(next(it)==attributes.end()){ //if it is
outFile << endl; //print a new line
}
}
if(attributes.size()>1) //closing the array
{
outFile << "]" << endl;
}
//outFile<<"]"<<endl;
}

c++ vector iterator deference inconsistency

I have the following code. When dereference in line 5, I got wrong value of (*it)->sec. while in line 8, I can obtain correct value. The only difference I noticed is one is inside the for loop, the other is outside the for loop. Is there some subtle point I missing here. I basically want to obtain the member value of the first element in the vector. What's the correct way of obtaining the first (*it)->sec before(outside) the for loop?
void print_allAddresses(std::vector<EntryObj *> EntryObj_vec){
std::cout << "time(sec:microsec) dataType memoryValue" << std::endl;
std::vector<EntryObj *>::iterator it;
it = EntryObj_vec.begin();
std::cout << (*it)->sec << std::endl; //EntryObj_vec.front()->sec also wrong here.
for(it = EntryObj_vec.begin(); it != EntryObj_vec.end(); ++it){
if(!(*it)->parameters.empty()){
std::cout << (*it)->sec << "." << (*it)->microsecond << " ";
std::map<std::string, std::string>::iterator it_map;
for (it_map = (*it)->parameters.begin(); it_map != (*it)->parameters.end(); it_map++){
std::cout << "(" << it_map->first<< ")" << " " << it_map->second << std::endl;
}
}
}
return;
}