如何在 c++ 中的字符串数组中存储变量
How to store variables in a string array in c++
我很喜欢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;
}
剩下的部分我就活在
相关文章:
- 多维数组存储三种不同的数据类型?
- C++将原始字符数组存储在元组中
- 将十六进制字符数组存储在字节数组中,而无需更改为 ASCII 或其他任何东西
- 我正在编写一个代码来将 int 数组存储在文件中,然后用 c++ 检索它,但是检索第一项是假值,我该如何解决这个问题?
- 如何将元素的索引从2D数组存储到1D数组中,然后交换这些值
- 如何将JSON数组存储在Arduino程序中
- 如何在AVR(例如:ATMega)或Arduino微控制器上制作2D PROGMEM阵列的1D PROGMEM数组(存储
- 使用 char 数组存储数据
- 使用平面数组存储的元组容器
- 数组 存储并要求用户搜索它
- 将值从一个 char 数组存储到另一个 char 数组
- 如何使字符串数组存储在向量中
- 将构造的静态数组存储在多个文件中的内存中
- 将整数数组存储在堆上并通过指针访问它们
- c++声明一个数据类型的字节数组,该数组存储在字符串中
- 使用指针数组存储阶乘计算的所有中间结果
- 使用异构数组存储不同的子类
- 读取文件内容,存储在数组中,向数组添加更多内容,然后将新数组存储在文件C++中
- 尝试将复杂数组存储到类 c++ 中
- 在字节数组存储中嵌入 int/string