如何将外部文件中的值放入数组中
How do I put the values from an external file into an array?
我正在尝试读取一个外部文件,并将文件中的所有字符串放入字符串类型的数组中。
这是我的主要功能:
#include <iostream>
#include "ReadWords.h"
#include "Writer.h"
#include <cctype>
#include <string>
using namespace std;
int main() {
int count;
const int size = 10;
string word_search[size];
string word;
cout << "Please enter a filename: " << flush;
char filename[30];
cin >> filename;
ReadWords reader(filename);
while (reader.isNextWord()){
count = count + 1;
reader.getNextWord();
}
cout << "Please enter the name of the file with the search words: " << flush;
char filename1[30];
cin >> filename1;
ReadWords reader1(filename1);
while (reader1.isNextWord()) {
这就是我试图将字符串存储在一个名为word_search的数组中的地方,但目前还不能正常工作。如何在数组中存储字符串?
for(int i = 0; i < size; i++){
word_search[i] = word;
}
}
这是我打印数组内容的地方,看看我是否成功了。
cout << word_search << endl;
return 0;
}
这是所有方法都在一个名为ReadWords.cpp:的单独文件中声明的地方
#include "ReadWords.h"
#include <cstring>
#include <iostream>
using namespace std;
void ReadWords::close(){
wordfile.close();
}
ReadWords::ReadWords(const char *filename) {
//storing user input to use as the filename
//string filename;
wordfile.open(filename);
if (!wordfile) {
cout << "could not open " << filename << endl;
exit(1);
}
}
string ReadWords::getNextWord() {
string n;
if(isNextWord()){
wordfile >> n;
//cout << n << endl;
int len = n.length();
for(int i = 0; i < len ; i++) {
if (ispunct(n[i]))
{
n.erase(i--, 1);
len = n.length();
}
}
cout << n << endl;
return n;
}
}
bool ReadWords::isNextWord() {
if (wordfile.eof()) {
return false;
}
return true;
}
你可能是指
size_t count = 0;
while (reader.isNextWord()){
word_search[count] = reader.getNextWord();
++count;
}
此外,请考虑使用std::vector而不是数组。此外,变量"word"未使用。要打印内容,请使用
for (size_t i = 0; i < size; ++i)
cout << word_search[i] << endl;
相关文章:
- 在函数内部的声明中初始化数组,并在外部使用它
- C++编程从外部文本文件定义数组大小
- 声明后初始化类外部的数组
- C++ 外部对象数组
- 将多维数组传递给外部"C"函数为 void *
- C++ 在类外部分配 char 数组的索引
- 我可以清除外部声明为进一步使用的数组吗?
- 如何将外部文件中的数据保存到 2D 数组中?(C++)
- C++中"T 的未知边界数组"的外部声明
- 在 gcc 中使用数组参数编译外部"c"代码
- C++中的结构数组和外部文件
- C 编程从外部输入文件定义数组大小
- 使用数组外部地址的数组运算符
- 如何将值加载到外部共享数组中
- 如何将输入数组从外部文件传递到主程序中
- 用于循环通过未知大小的外部普通数组
- 减少从外部数据文件中检索字符数组的重复
- 为什么我的数组没有输出正确的数据,这些数据是从外部文件输入的?
- 如何外部化全局二维数组
- 如果不使用数组外部的数据,访问数据是否不正确?