简体   繁体   English

如何在C ++中将变量存储在字符串数组中

[英]How to store variables in a string array in c++

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. 我非常熟悉C ++,最近完成了一项作业,我需要将1000个最常用的单词存储到字符串数组中。 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. 上面的for循环在开始时不执行任何操作,只是在第一次迭代时中断。 It would be better if you'll read how to use loops in C++. 如果您将阅读如何在C ++中使用循环会更好。 Also take a look at the scopes of the variables in C++. 还请看一下C ++中变量的范围。 In your case commonWords declared in while loop, so will be created each time and destroyed after each loop iteration. 在您的情况下,在while循环中声明的commonWords会因此每次创建并在每次循环迭代后销毁。 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. 我将为您完成剩余的工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM