i am trying to put the words that there are in a txt file* into an array of strings. But there is an error with the strcpy(). it sais: 'strcpy' : cannot convert parameter 1 from 'std::string' to 'char *' . Why is that? Isn't it possible to create an array of strings like this in 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();
}
I suggest strcpy (p[i], word);
be changed to p[i] = word;
. This is the C++ way of doing things and takes advantage of the std::string
assignment operator.
You don't need strcpy
here. A simple assignment will do it: p[i] = word;
. strcpy
is for C-style strings, which are null-terminated arrays of characters:
const char text[] = "abcd";
char target[5];
strcpy(target, text);
Using std::string
means you don't have to worry about getting the size of the array right, or about calling functions like strcpy
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.