[英]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;
}
写入第一个字符串,但第二个字符串未显示在文本文档中
您似乎在寻找:
myfile << vertexcharacter << a;
当前,您正在使用逗号运算符,因此您的行等效于:
(myfile << vertexcharacter), a;
这vertexcharacter
插入myfile
,丢弃结果,然后求值a
,它什么也不做。
简短答案: myfile << vertexcharacter << a;
逗号执行的操作与您期望的完全不同。 逗号有点像分号。 如果您有多个用逗号分隔的语句,则每个语句将按顺序执行。 但是最后一个语句是其值被“返回”的语句。 例如:
int x = 3;
cout << (x+=2, x+5);
在这种情况下,执行x+=2
使得x = 5,然后“返回” x+5
,因此将值10插入到cout中。 另一方面,您的示例等效于
(myfile << vertexcharacter), a;
基本上,将vertexcharacter
插入到myfile
,然后,如果您以某种方式捕获了结果,例如x = (myfile << vertexcharacter, a);
那么您将得到x = a。 您真正想要的是myfile << vertexcharacter << a;
一定是
myfile << vertexcharacter << a;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.