C++中按行讀取文本數據


C++中按行讀取文本數據



假設文本數據例如爲:
2 55 8
22 55 2
1 12 3
8 5 66


    #include <fstream>
    #include <sstream>
    #include <iostream>
    #include <string>
    
    //定義文件路徑
	string strFileName = "case5.txt";/*文件路徑*/
	
	//定義一個文件流
	ifstream FileIn(strFileName, ifstream::in);


	//讀取一行保存整行數據到這個string
	string strLine;


    //循環讀取數據
	while (getline(FileIn, strLine))
	{
		//定義一個string流
		istringstream StringIn;
		StringIn.str(strLine);   //將strLine拷貝到StringIn中


		//讀到空行跳出
		if (strLine == "")
		{
			break;
		}
		
		//依次將數據讀入到3個int變量中
		StringIn >> m_iVertextNum >> m_iArcNum >> m_iConsumerNum;
    }

當然有更簡單的讀取方式,直接採用C++的文件輸入流,用輸出操作符>>實現

    #include <fstream>
    #include <iostream>
    #include <string>
    
    //定義文件路徑
	string strFileName = "case5.txt";/*文件路徑*/
        int a, b;
	ifstream FileIn(path);
	while (contourFile >> x >> y)
	{
		a = x;
		b = y;
		
	}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章