【发布时间】: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<std::string>使其成为C++,不要使用从文件中读取的字符,而是使用简单的>>并在必要时拆分为非字母字符(您的文本文件示例将有助于建议最好的方法在这里) -
该文件确实存在..它是家庭作业的一部分:),单词肯定也是 319。 txt 文件中的单词也是每个车道一个。
-
想象一下可能有一个涉及更大文件的以下练习。你真的想重写你的代码吗?不,您希望代码能够处理各种文件。关键是偷懒,不要硬编码这些数字。
-
您完全正确,您建议为此使用数组列表?
-
我推荐
std::vector为此目的,但任何动态存储都可以。