如何用C++从.txt文件中读取数据写入数组

sunxden 2011-03-01 07:06:03

input.txt
第一行:5
第二行:2.3 3.1 7.5 1.5 6.3



先读出整型数据5,初始化浮点型数组 float *num = new float[5];

然后把第二行里面的数据依次读出赋给num[0],...,num[4];

用C++如何实现?主要是如何读出第二行的数据(不会把第一行的数据掺进来)!!
...全文
3148 16 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
16 条回复
切换为时间正序
请发表友善的回复…
发表回复
辰岡墨竹 2011-03-03
  • 打赏
  • 举报
回复
>>和<<在处理时,会根据另外的操作符的类型来进行,如果是整数或浮点类型就忽略空白。如果是字符或字符串,就不会忽略了。
tomatobin 2011-03-03
  • 打赏
  • 举报
回复
#include<iostream>
#include<fstream>
#include<cstdlib>
using namespace std;
int main()
{
ifstream infile("data.txt");
if (infile.is_open())
{
int total;
infile>>total;
double *num=new double[total];
while (!infile.eof())
{
infile >> *num;
cout<<*num << '\t';
num++;
}
}

else
{
cout<<"Error,can't open...\n";
exit(2);
}

return 0;
}
zwwjoy 2011-03-03
  • 打赏
  • 举报
回复

CFileException pError;
CString strLineCont;
if (TRUE == m_stdFileEx.Open("input.txt", CFile::modeRead|CFile::typeText, &pError))
{

while(m_stdFileEx.ReadString(strLineCont)) //逐行读取内容到strLineCont中
{
//你自己的操作

}
m_stdFileEx.Close();
return true;
}
else
{
MessageBox(NULL,_T("文件不能读入\n文件正在打开或使用中!"),_T("读取文件失败"), MB_OK|MB_ICONINFORMATION);
return false;
}
Joyfulmath 2011-03-02
  • 打赏
  • 举报
回复
换行应该是0x0d0a
Crazy_hand 2011-03-02
  • 打赏
  • 举报
回复
#include <sstream>

istringstream;
ostringstream;
sunxden 2011-03-01
  • 打赏
  • 举报
回复
[Quote=引用 10 楼 delphiwcdj 的回复:]

引用 9 楼 sunxden 的回复:

我现在明白了,">>" 与 "<<"运算符会自动忽略 '\n'和空格。之前这个问题困扰了我好久的,唉,现在终于想通了。

会忽略空白
[/Quote]

‘\n'难道不会被忽略么?
delphiwcdj 2011-03-01
  • 打赏
  • 举报
回复
[Quote=引用 9 楼 sunxden 的回复:]

我现在明白了,">>" 与 "<<"运算符会自动忽略 '\n'和空格。之前这个问题困扰了我好久的,唉,现在终于想通了。
[/Quote]
会忽略空白
sunxden 2011-03-01
  • 打赏
  • 举报
回复
我现在明白了,">>" 与 "<<"运算符会自动忽略 '\n'和空格。之前这个问题困扰了我好久的,唉,现在终于想通了。
delphiwcdj 2011-03-01
  • 打赏
  • 举报
回复
[Quote=引用 4 楼 proghua 的回复:]

C/C++ code
ifsream inputfile("input.txt");
int count ;
inputfile >> count;
for (int i = 0; i < count; i++)
inputfile >> num[i];
[/Quote]
这种方法比较简单,用fscanf也可以,只要格式是固定的,就一个一个读,然后存入不同的变量里
ryfdizuo 2011-03-01
  • 打赏
  • 举报
回复
	ifstream infile;
infile.open ("test.txt");
if (infile.is_open())
{
int num;
float *pf, *p;

infile >> num;
pf = new float[num];
p = pf;

while (infile.good()) {
infile >> *p++;
cout << *(p-1) << endl;
}

infile.close();
}
else
{
cout << "Error opening file";
}
「已注销」 2011-03-01
  • 打赏
  • 举报
回复
ACM程序的测试用例,都是这种格式的
「已注销」 2011-03-01
  • 打赏
  • 举报
回复
ifsream inputfile("input.txt");
int count ;
inputfile >> count;
for (int i = 0; i < count; i++)
inputfile >> num[i];
sunxden 2011-03-01
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 bdmh 的回复:]

因为你每行数据量不定,所以你还是根据空格解析出来吧
如果固定的话,可以用fscan来取
[/Quote]

我应该如何来根据空格解析? 能否再详细些?
bdmh 2011-03-01
  • 打赏
  • 举报
回复
因为你每行数据量不定,所以你还是根据空格解析出来吧
如果固定的话,可以用fscan来取
sunxden 2011-03-01
  • 打赏
  • 举报
回复
这个读取数据老师没讲,但现在要用到这方面的东西,有人帮忙么?

65,184

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧