当前位置:编程学习 > VC++ >>

请问在VC中怎样把一个txt文件中的十进制数据读到一个数组中

这个txt文件中内容是这样的1 -7 6 16 16 0 4 15 17 9 0 13 18 11 -1 0 18 13 2 -11 0 15 4 -9 -17 0 7 -6 -16 -16 0 -4 -15 -17 -9 0 -13 -18 -11 1 0 -18 -13 -2 11 0 -15 -4 9 17 0 -7 6 16 16 0 4 15 17 9 0 13 18 11 -1 0 18 13 2 -11 0 15 4 -9 -17 0 7 -6 -16 -16 0 -4 -15 -17数据之间以空格分隔,求助大神!
答案:你可以开一个大数组,也可以动态分配。
假定数据在 a.txt 里,空格分隔,每行数的个数 任意。
#include <stdio.h>
#include <stdlib.h>
FILE *fin;
void main()
{
int *x;
int i,k,NN;
fin=fopen("a.txt","r");   // 打开文件
NN=0;
while (1){
if  (fscanf(fin,"%d",&k) ==EOF) break;
NN++;   // 统计数据个数
}
x = (int *) malloc(sizeof(int) * NN);  //动态分配
rewind(fin);   // 回绕文件
for (i=0;i<NN;i++) fscanf(fin,"%d",&x[i]) ;   // 读入 x[i]
fclose(fin);  //关文件
for (i=0;i<NN;i++) printf("%d\n",x[i]);  // 屏幕输出数据
}
其他:# include <windows.h>
# include <stdlib.h>
# include <vector>

const wchar_t szFilePath[] = L"C:\\Users\\Turein\\Desktop\\a.txt";
const wchar_t cSpace = L' ';
HANDLE hFile = NULL;
int __stdcall wWinMain(  HINSTANCE ,  HINSTANCE ,  LPWSTR ,  int  )
{
	std::vector<int> intArray;
	std::vector<wchar_t> strNumber;
	std::vector<wchar_t> fileBuffer;
	hFile = CreateFile(szFilePath,GENERIC_READ,FILE_SHARE_READ,
		NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL, NULL);                
	if (hFile == INVALID_HANDLE_VALUE) 
		return 0;
	DWORD hiBytes = 0;
	DWORD lowBytes = ::GetFileSize(hFile, &hiBytes);
	if( (lowBytes <= 0) && (hiBytes <= 0) )
		return 0;
	fileBuffer.resize(lowBytes / 2);
	DWORD dwRead = 0;
	::ReadFile(hFile, &fileBuffer[0], lowBytes, &dwRead, NULL);
	::CloseHandle(hFile);
	hFile = NULL;                                            
	//////////////////////////////////////////////////////////////////////////
	//将文件内容读取到fileBuffer中

	for(int i = 0; i < fileBuffer.size(); ++i)
	{
		wchar_t t = fileBuffer[i];
		if(iswxdigit((int)t) || t == L'-')
			strNumber.push_back(t);
		if(cSpace == fileBuffer[i])
		{
			strNumber.push_back(0);
			intArray.push_back(_wtoi(&strNumber[0]));
			strNumber.clear();
		}
	}
	strNumber.push_back(0);
	intArray.push_back(_wtoi(&strNumber[0]));
	strNumber.clear();
	fileBuffer.clear();
	////////////////////////////////////////////////////////////////////
	///将fileBuffer中的内容转换为int向量


	int* intPointer = new int[intArray.size()];
	memcpy(intPointer, &intArray[0], sizeof(int) * intArray.size());
	intArray.clear();
	////////////////////////////////////////////////////////////////////
	///将int向量转换为C++数组
	/// 
	delete []intPointer;
	return 0;
} 
给你一个STL实现版,这个版本的主要方法都是STL和WIN32函数实现的,拥有工业级强度与可靠性。注意这是一个Windows程序不要在控制台下编译。
程序首先将文件作为一块大数据读入内存,然后关闭文件。
接着遍历这片内存,如果当前元素为数字或者负号就从strNumber尾部插入。如果为空格,就从strNumber头部将其转换为字符串并加入intArray表。判断过程是必要的,如果你用记事本按unicode保存数字,会出现一些干扰字符。
最后将存放结果的intArray转换为int*类型。 

上一个:vc2010“Automation服务器不能创建对象”?
下一个:运行一个写卡的VC小程序程序后提示没有找到MFC42D.DLL

CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,