【问题标题】:CSV data into Form controlCSV 数据导入表单控件
【发布时间】:2012-02-27 07:26:49
【问题描述】:

我正在使用 this answer 中的代码读取 CSV 文件,并且我想将 const CSVRow& row 值分配给表单控件(例如 ListBox)。我怎样才能做到这一点?

这是我要更改的代码:

void display(const CSVRow& row)
{
    if(!row.size()) return;
    CSVRowCI i = row.begin();
    std::cout << *(i++); 
    for(; i != row.end(); ++i)
        std::cout << ',' << *i;
}

但我想做的不是std::cout &lt;&lt; ',' &lt;&lt; *i,而是:

this->ListBox1->Items->Add(*i);

我尝试使用*i.ToString(),但它给了我一个错误:

无法将 const std::basic 字符串转换为 System::String

【问题讨论】:

标签: c++ c++-cli


【解决方案1】:

我看到CSVRowCI 类型实际上是一个typedef,表示std::vectorstd::strings 中的一个单独的std::string 元素。既然你想在C++/CLI WinForms 应用程序中使用这个代码,你需要先将其转换为System.String(因为这是Add() 方法所期望的)。也许你可以做一些类似的事情:

String^ myString= gcnew String(*i.c_str());
myListBox->Items->Add(myString);

我对 C++/CLI 不是很熟悉,所以可能有更好的方法将 std::string 转换为 System.String

【讨论】:

  • 那么如何将其转换为 System.String?
  • 我已经在答案中描述了一种从std::string 转换为System.String 的方法。您是否完整阅读了答案?
  • 感谢您的回复。但我尝试了你的方法,但它给出的错误如下: 1. 'c_str' : is not a member of 'std::_Vector_const_iterator<_ty>'... 2. 'gcnew' 只能用于创建一个对象托管类型.... 3. 'String' : 模棱两可的符号 4.'^' : 不能在类型 'String' 上使用这种间接寻址
  • @amritaJaiswal :std::vector 中包含什么?如果vector 不包含std::strings,那么您将遇到问题。请发布导致错误的确切代码。上面的答案基于对this 帖子的简短分析。因此,如果您的代码与其不同,则可能需要进一步更改才能使其正常工作。
  • @amritaJaiswal :如果您完全按照原样使用代码,那么我猜 typedef std::string String; 行可能会导致一些问题,因为 String 是 CLI 类型,所以请尝试使用其他标识符对于typedef 声明。
【解决方案2】:

您正在实施的答案似乎有缺陷。可以在 CSV 字段中嵌入逗号,但答案似乎无法识别。

也许您知道您的数据永远不会嵌入逗号,在这种情况下不应该有问题。但我有一个旧版本that I've posted online,它演示了一些应该采取的额外步骤。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-21
    • 1970-01-01
    • 1970-01-01
    • 2012-04-17
    • 2015-06-30
    相关资源
    最近更新 更多