当我将setw()与ofstream一起使用时,它没有正确地写入文件。它跳过了许多输出行,在Notepad++中,输出文件显示了大量的NULL。但是当我用"\t"来尝试它时,它工作得很好。
你能解释一下为什么吗?
#include<fstream>
#include<iomanip>
using namespace std;
int main(){
ofstream myfile;
myfile.open ("test.txt");
for(int i=0;i<300;i++){
myfile <<"\n"<<setw(15)<<0<<setw(15)<<0<<setw(15)<<10000<<setw(15)<<6000;
//myfile <<"\n\t"<<0<<"\t"<<0<<"\t"<<10000<<"\t"<<6000;
}
return 0;
}编辑:
我进行了更多的测试,发现问题是特定于下面的配置的。我使用ubuntu客户在win7上使用virtualbox,我的程序试图使用在ubuntu上挂载的virtualbox共享文件夹在主机OS驱动器上编写文件。
当我试图在ubuntu内部运行程序时,它运行得很好。此外,我也尝试在我的个人计算机上做同样的事情,它也有win7主机和ubuntu来宾。我在一个从win7到ubuntu的挂载驱动器上尝试了相同的程序,它工作得很好。
我想知道是不是因为我工作电脑上的设置。不管怎么说,现在不重要了。但更多的见解是值得欢迎的。
发布于 2016-06-24 09:27:42
解决方案可能是确保确实使用空格(或其他字符)来设置数据之间的宽度:
#include<fstream>
#include<iomanip>
using namespace std;
int main(){
char a='î';
int b=15;
ofstream myfile;
myfile.open ("test.txt");
for(int i=0;i<3;i++){
myfile <<'\n' <<setfill(a)<<setw(b)
<<0 <<setfill(a)<<setw(b)
<<0 <<setfill(a)<<setw(b)
<<10000 <<setfill(a)<<setw(b)
<<6000 ;
}
myfile <<'\n';
return 0;
}给出
$ g++ a.cpp -std=c++0x -Wall -o a && ./a & cat test.txt
::::::::::::::0::::::::::::::0::::::::::10000:::::::::::6000
::::::::::::::0::::::::::::::0::::::::::10000:::::::::::6000
::::::::::::::0::::::::::::::0::::::::::10000:::::::::::6000https://stackoverflow.com/questions/9916661
复制相似问题