1. 程式人生 > >VS2013 C++/ Winform textBox 讀txt文字 顯示多行

VS2013 C++/ Winform textBox 讀txt文字 顯示多行

  讀取txt檔案逐行:

   法一:

#include <iostream>
#include <fstream>
#include <cassert>
#include <string>


	////////////////////////// 法一
				 set_xunfei_param();//引數設定
				 string file = "C:\\Users\\jingling\\Desktop\\1.txt";  //路徑設定

				 ifstream infile;
				 infile.open(file.data());   //將檔案流物件與檔案連線起來 
				 assert(infile.is_open());   //若失敗,則輸出錯誤訊息,並終止程式執行

				 string s;
				 while (getline(infile, s))
				 {
					 txt_speak->Text = gcnew String(s.c_str());
				 }
				 infile.close();             //關閉檔案輸入流 
/////////////////////////
法二:
/////////////////////////法二
				 /*char *filePath = "C:\\Users\\jingling\\Desktop\\1.txt";  //路徑設定

				 ifstream file;
				 file.open(filePath, ios::in);
				 //assert(infile.is_open());   //若失敗,則輸出錯誤訊息,並終止程式執行
				 
				std::string strLine;
				while (getline(file, strLine))
				{
					if (strLine.empty())
						continue;
					txt_speak->Text = gcnew String(strLine.c_str());
				}

				 file.close();             //關閉檔案輸入流 */


	     	///////////////////////////////
若txt的檔案內容是:

  423,

  265,

  456,

  123,

 法一和法二的結果是,textBox只顯示一行:123,

	     	///////////////////////////////
				 char *filePath = "C:\\Users\\jingling\\Desktop\\1.txt";  //路徑設定

				 ifstream file;
				 file.open(filePath, ios::in);

				 std::string strLine;

				 while (getline(file, strLine))
				 {
				    if (strLine.empty())
				    continue;
					txt_speak->Text = txt_speak->Text + gcnew String(strLine.c_str());
				 }

				 file.close();             //關閉檔案輸入流 

把法一法二中的:

txt_speak->Text = gcnew String(strLine.c_str());

改為:

txt_speak->Text = txt_speak->Text + gcnew String(strLine.c_str());

textBox結果:

     423,256,456,123,