2015-07-04 29 views
-2

我試圖讀入一個文本文件到我的程序中,以便我可以填充我已連接到我的程序的mysql數據庫。在我可以將它發送到數據庫之前,我需要能夠逐個讀取每個字符串,而不是讀取整個行。我是新來的使用visual c + +和窗體,所以任何幫助,將不勝感激。C++/cli讀取文本文件

int main(array<System::String ^> ^args) 
{ 

    String^ fileName = "customerfile.txt"; 
    try 
    { 
     MessageBox::Show("trying to open file {0}...", fileName); 
     StreamReader^ din = File::OpenText(fileName); 

     String^ str; 
     int count = 0; 
     while ((str = din->ReadLine()) != nullptr) 
     { 
      count++; 
      MessageBox::Show(str); 
     } 
    } 

我試圖從被格式化這樣閱讀的文本文件:

43約翰·史密斯4928烏節路。邁阿密佛羅里達州

我想消息框顯示43,然後一個新的消息框顯示約翰,等等。現在它顯示整條線。

+3

這不是C++。 –

+0

它是C++/CLI。我正在使用它來製作窗體,我無法使用c# –

+0

那麼爲什麼你的問題說C++ lol –

回答

0

這裏有一個方法:

Parse Strings Using the Split Method

using namespace System::Diagnostics; 
//... 

String^ fileName = "customerfile.txt"; 
StreamReader^ din = File::OpenText(fileName); 

String^ delimStr = " ,.:\t"; 
array<Char>^ delimiter = delimStr->ToCharArray(); 

String^ str; 
int count = 0; 
while ((str = din->ReadLine()) != nullptr) 
{ 
    count++; 

    array<String^>^ words; 
    words = str->Split(delimiter); 
    for (int word = 0; word<words->Length; word++) 
    { 
     if (!words[word]->Length) // skip empty words 
      continue; 
     Trace::WriteLine(words[word]); 
    } 

} 

您可以設置delimStr = " ";如果你只是想使用空格分割。如果要使用空格和逗號分割,,則將其更改爲delimStr = " ,";等等。