C++:依次读取TXT文件各行数据

// FileHandle.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>

int main()
{
	std::string GroupNumberStr;
	std::string GroupIDStr;
	std::string MessageContextStr;

	int64_t GroupNumber = 0;
	int64_t GroupID = 0;

	//文本应使用UTF-8类型编码
	std::ifstream GrouIDList("GroupIDList.txt", std::ios::in);
	std::ifstream MessageContext("MessageContext.txt", std::ios::in);

	if (!GrouIDList)
	{
		std::cout << "GrouIDList is NULL." << std::endl;
		return 0;
	}

	if (!MessageContext)
	{
		std::cout << "MessageContext is NULL." << std::endl;
		return 0;
	}

	getline(GrouIDList, GroupNumberStr);

	std::cout << GroupNumberStr << std::endl;
	GroupNumber = atoi(GroupNumberStr.c_str());

	std::cout << GroupNumber << std::endl;

	MessageContext.close();
	while (GroupNumber--)
	{
		if (!std::getline(GrouIDList, GroupIDStr))
		{
			GrouIDList.close();
			return 0;
		};
		std::cout << GroupIDStr << std::endl;
		GroupID = atoi(GroupIDStr.c_str());
		std::cout << GroupID << std::endl;
		if (GroupID)
		{

		}
	}
	GrouIDList.close();

	system("pause");
    return 0;
}

注意:如果是要读取一个文件应该使用ifstream,如果要写入一个文件应该使用ofstream。

测试结果:

猜你喜欢

转载自blog.csdn.net/xikangsoon/article/details/86356833