I am quite in to C++ and have a recent homework assignment which I need to store 1000 most common words into a string array. I was wondering how would I go about this. Here is my example code so far,
if(infile.good() && outfile.good())
{
//save 1000 common words to a string
for (int i=0; i<1000; i++)
{
totalWordsIn1000MostCommon++;
break;
}
while (infile.good())
{
string commonWords[1000];
infile >> commonWords;
}
}
Thanks!
#include <cstdio>
#include <string>
freopen(inputfileName,"r",stdin);
const int words = 1000;
string myArr[words];
for(int i=0;i<words;i++){
string line;
getline(cin,line);
myArr[i] = line;
}
The for
loop above does nothing at the beginning, just breaks at first iteration. It would be better if you'll read how to use loops in C++. Also take a look at the scopes of the variables in C++. In your case commonWords declared in while
loop, so will be created each time and destroyed after each loop iteration. What you want is something like this:
int i = 0;
std::string commonWords[1000];
while (i < 1000 && infile.good()) {
infile >> commonWords[i];
++i;
}
I'm living the remaining part for you to complete your homework.
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.