user1887092
user1887092

Reputation: 83

How do you write two strings to a file in c++

{
    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

Answers (4)

Mayhem
Mayhem

Reputation: 396

It must be

myfile << vertexcharacter << a;

Upvotes: 0

Lorkenpeist
Lorkenpeist

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

juanchopanza
juanchopanza

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

Joseph Mansfield
Joseph Mansfield

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

Related Questions