2013-03-21 65 views
1

我的任务是在单击按钮后打开多个文件,并阅读所有这些选定的文件。如何解决“每个”循环中的“字符串”

我在c#中找到了一个foreach函数的例子,但我想用C++编写它。我应该如何转换?

它显示了错误System::String,不能在没有顶级'^'的情况下使用此类型。

我还是那个新手。有人可以提供建议吗?

非常感谢。

下面是我写的代码

Stream^ myStream; 
OpenFileDialog^ openFileDialog1 = gcnew OpenFileDialog; 

openFileDialog1->InitialDirectory = "c:\\"; 
openFileDialog1->Title = "open captured file"; 
openFileDialog1->Filter = "CP files (*.cp)|*.cp|All files (*.*)|*.*|txt files (*.txt)|*.txt"; 
openFileDialog1->FilterIndex = 2; 
//openFileDialog1->RestoreDirectory = true; 
openFileDialog1->Multiselect = true; 

if (openFileDialog1->ShowDialog() == System::Windows::Forms::DialogResult::OK) 
{ 
    **for each (String line in openFileDialog1->FileName)** 
     System::Diagnostics::Debug::WriteLine("{0}",line); 
    myStream->Close(); 
} 

回答

0

根据容器类型返回,存在<algorithm> -header定义的std::for_each。 功能如下:

#include <algorithm> 

std::for_each(InputIterator first, InputIterator last, Function fn); 

您需要提供两个iterators,一个集装箱的开始,一个用于迭代结束。作为第三个参数,您可以提供一个函数(函数对象)并对当前参数进行操作。

参见here以供进一步参考。

因为我从MSDN得到它,所以SafeFileNames返回array<String^>

System::Array提供了一种称为Array::ForEach的静态方法。你会需要调用它像

System::Action<T> myAction; // You will Need to provide a function here to be used on every filename. 
System::Array::ForEach(openFileDialog1->SafeFileNames, myAction); 

这是最接近foreach从C#。

Look here for System::Array::ForEach and here for OpenFileDialog::SafeFileNames

+0

这是否适用于WinAPI格式? – Ken 2013-03-21 20:05:12

+1

这属于'C++ - STL',所以便携。你可以在那里使用它,不用担心。 – 2013-03-21 20:06:50

+0

唯一的办法是?我经历了你给定的链接后,我不太明白这一点。对不起,如果这个问题有点愚蠢,因为我还很新。无论如何,非常感谢你的时间。 – Ken 2013-03-21 20:12:35

相关问题