各位前辈,最近在学C++文件流,在读取一个文件时我遇到了一些问题
文件的内容是这样的:
0 9 10 3 0
7 6 2 1 1
9 3 3 1 1
13 9 3 3 0
我想把这里面的数字都放到一个数组里
我读取它的一段代码是这样的:
ifstream fp("map1.txt",ios::in);
if(!fp)
cout<<"error occours";
char temp[55];
for(int i=0;i fp>>temp[i];
//显示数组内容
for(int j=0;j<55;j++)
{
cout<<temp[j]<<" ";
if(0==j%4)
cout<<endl;
}
我发现这样读出来之后,那些双数,比如第三个数10,它就分成了两个数“1”和“0”
来读取,那么本来我想temp[2]==10的,现在变成temp[2]==1,temp[3]==0了
请问各位前辈有没有什么好的方法解决这个问题,谢谢了!
操纵符 功能 输入/输出
dec 格式化为十进制数值数据 输入和输出
endl 输出一个换行符并刷新此流 输出
ends 输出一个空字符 输出
hex 格式化为十六进制数值数据 输入和输出
oct 格式化为八进制数值数据 输入和输出
setpxecision(int p) 设置浮点数的精度位数 输出
比如要把123当作十六进制输出:file1<<hex<<123;要把3.1415926以5位精度输出:file1<<setpxecision(5)<<3.1415926。
ifstream fp("map1.txt",ios::in);
if(!fp)
cout<<"error occours";
char temp[55];//你这个是char型的,每次都只接收一个字符 10是两个字符,读进来肯定会分开的
for(int i=0;i fp>>temp[i];
//显示数组内容
for(int j=0;j<55;j++)
{
cout<<temp[j]<<" ";
if(0==j%4)
cout<<endl;
}
建议每次读一行,然后用空格的方式把他们分开!最后可以转成int型
你的那个fp>>temp[i],是一个字符一个字符读取的
可以把temp的数据类型换成整型。
详细请看以下代码,编译执行都通过。
#include
#include
using namespace std;
void main()
{
//打开文件
ifstream fp;
fp.open("map1.txt",ios::in);
if(!fp)
cout<<"error occurs";
int temp[128];
//读取文件,直到文件末尾
int i=0;
while (!fp.eof())
{
fp>>temp[i];//读取整型数字
++i;
}
//关闭文件
fp.close();
//显示数组内容,i为数字的有效个数
for(int j=0;j<i;j++)
{
cout<<temp[j]<<" ";
if ((j+1)%5==0) //换行
{
cout<<endl;
}
}
}
这个应该用getline搞到字符串里面分析把,按照空格截取,你们fp重定向到temp【】可以搞么?