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;
		
	}


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