Reputation: 83
{
string vertexcharacter = "{";
string a = "}";
ofstream myfile;
myfile.open("newfile.txt");
myfile << vertexcharacter, a;
myfile.close();
system("pause");
return 0;
}
the first string is written but the second string does not show up in a text document
Upvotes: 0
Views: 134
Reputation: 1495
Short answer: myfile << vertexcharacter << a;
The comma does something very different than what you expect. Think of comma kind of like a semicolon. If you have multiple statements strung together by commas, each statement will be executed in order. But the last statement is the one whose value is "returned". For example:
int x = 3;
cout << (x+=2, x+5);
In this case, x+=2
executes so that x=5, and then x+5
is "returned", so the value 10 is inserted into cout. Your example, on the other hand, is equivalent to
(myfile << vertexcharacter), a;
Basically, vertexcharacter
is inserted into myfile
, and then, if you were capturing the result somehow, like x = (myfile << vertexcharacter, a);
then you would get x=a. What you really want is myfile << vertexcharacter << a;
Upvotes: 0
Reputation: 227418
Like this:
myfile << vertexcharacter << a;
What you currently have
myfile << vertexcharacter, a;
involves the comma operator, which evaluates the first argument (myfile << vertexcharacter
), discards the result, then evaluates the second argument (a
). The reason for this is that the comma operator has the lowest precedence.
Upvotes: 3
Reputation: 110658
You appear to be looking for:
myfile << vertexcharacter << a;
Currently, you're using the comma operator, so your line is equivalent to:
(myfile << vertexcharacter), a;
This inserts vertexcharacter
into myfile
, discards the result, then evaluates a
which does nothing.
Upvotes: 4