如何在 c++ 中的字符串数组中存储变量

How to store variables in a string array in c++

本文关键字:数组 存储 变量 字符串 c++      更新时间:2023-10-16

我很喜欢C++,并且最近有一个家庭作业,我需要将 1000 个最常见的单词存储到一个字符串数组中。我想知道我将如何去做这件事。这是我到目前为止的示例代码,

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;
        }
    }

谢谢!

   #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;      
   }

上面的for循环在开始时什么都不做,只是在第一次迭代时中断。如果您能阅读如何在C++中使用循环,那就更好了。另请查看 C++ 中变量的作用域。在你的例子中,commonWords while循环中声明,所以每次都会创建并在每次循环迭代后销毁。你想要的是这样的东西:

int i = 0;
std::string commonWords[1000];
while (i < 1000 && infile.good()) {
    infile >> commonWords[i];
    ++i;
}

剩下的部分我就活在

你身上,让你完成作业。