1. 程式人生 > >C++:依次讀取TXT檔案各行資料

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。

測試結果: