2015-07-04 71 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 = " ,";等等。