【问题标题】:strcpy c++ cannot convert parameter 1 from string char*strcpy c++ 无法从字符串 char* 转换参数 1
【发布时间】:2013-04-06 17:01:58
【问题描述】:

我正在尝试将 txt 文件*中的单词放入字符串数组中。 但是 strcpy() 有一个错误。它说:'strcpy':无法将参数 1 从 'std::string' 转换为 'char *'。这是为什么?在c++中不能创建这样的字符串数组吗?

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

void ArrayFillingStopWords(string *p);

int main()
{
   string p[319];//lekseis sto stopwords
   ArrayFillingStopWords(p);
   for(int i=0; i<319; i++)
   {
       cout << p[i];
   }
   return 0;
}

void ArrayFillingStopWords(string *p)
{
    char c;
    int i=0;
    string word="";
    ifstream stopwords;
    stopwords.open("stopWords.txt");
    if( stopwords.is_open() )
    {
       while( stopwords.good() )
       {
           c = (char)stopwords.get();
           if(isalpha(c))
           {
               word = word + c;
           }
           else
           {
               strcpy (p[i], word);//<---
               word = "";
               i++;
           }
       }
   }
   else
   {
       cout << "error opening file";
   }
   stopwords.close();
}

【问题讨论】:

  • 你真的应该考虑重构你的阅读方法。如果文件不存在怎么办?您真的要显示 319 个空字符串吗?你确定你总能得到 319 个单词吗?为什么不是 318(甚至更糟)的 320?使用std::vector&lt;std::string&gt; 使其成为C++,不要使用从文件中读取的字符,而是使用简单的&gt;&gt; 并在必要时拆分为非字母字符(您的文本文件示例将有助于建议最好的方法在这里)
  • 该文件确实存在..它是家庭作业的一部分:),单词肯定也是 319。 txt 文件中的单词也是每个车道一个。
  • 想象一下可能有一个涉及更大文件的以下练习。你真的想重写你的代码吗?不,您希望代码能够处理各种文件。关键是偷懒,不要硬编码这些数字。
  • 您完全正确,您建议为此使用数组列表?
  • 推荐 std::vector为此目的,但任何动态存储都可以。

标签: c++ strcpy


【解决方案1】:

我建议将strcpy (p[i], word); 改为p[i] = word;。这是 C++ 的处理方式,并利用了 std::string 赋值运算符。

【讨论】:

  • 这行得通..我以为除了 strcpy 之外我没有其他选择。谢谢
【解决方案2】:

这里不需要strcpy。一个简单的任务就可以做到:p[i] = word;strcpy 用于 C 风格的字符串,它们是以 null 结尾的字符数组:

const char text[] = "abcd";
char target[5];
strcpy(target, text);

使用std::string 意味着您不必担心数组大小是否正确,也不必担心调用strcpy 之类的函数。

【讨论】:

    猜你喜欢
    • 2015-06-12
    • 1970-01-01
    • 1970-01-01
    • 2012-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-25
    • 1970-01-01
    相关资源
    最近更新 更多