【发布时间】:2015-06-16 15:11:21
【问题描述】:
我正在尝试在字符串类数组中插入几个字符串类数组(取自输入文件)。
我正在编写的程序包含一个 Dictionary 类,其中默认构造函数将文件名(例如“words.txt”)作为参数,从而将每个单独读取的单词存储到 String 类中的单个元素中大批。 文本文件看起来像:
example
text
file
here
etc...
我为测试它而编写的代码(根本不起作用)如下:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
class Dictionary(const char *file) {
public:
string wordList;
int numWords;
};
Dictionary::Dictionary(const char *file) {
ifstream inFile;
int SIZE = 50000;
char pass[SIZE+1];
numWords = 0;
inFile.open(file);
if(!inFile)
cout << "File can not be opened" << endl;
else
while(inFile.getline(pass, SIZE)){
wordList[numWords] = pass[SIZE+1];
numWords++;
}
}
inFile.close();
cout << wordList[5] << endl;
cout << numWords << endl;
}
int main(){
Dictionary *foo = new Dictionary("words.txt");
};
代码编译但打印:
//should print out the 5th word in the file but nothing
0
我想知道我到底错过了什么?我一夜之间一直在努力解决这个问题,我觉得解决方案很简单,但我没有抓住重点。
我的主要问题似乎是在我的其他试验中打印出的错误消息,涉及“从 'char*' 到 'char' 的无效转换。此外,程序中未显示的其他函数需要每个单词的字母要操作的String类数组的元素(最好是字符串类数组而不是C字符串)。我在这里迷路了。请帮忙?
我找到了这个有用的链接,但它适用于 Java。 C++ 的等价物是什么? http://www.mathcs.emory.edu/~cheung/Courses/170/Syllabus/09/String-array.html
【问题讨论】:
-
Dictionary *foo = new Dictionary("words.txt");你需要收起 Java 书籍:这里是 C++:Dictionary foo("words.txt");其次,将文件中的单词整理成数组基本上是一个 3 行程序(可能更少)。你不需要整个班级。 -
我将它作为一个类写在这里,因为我将在另一个类中实现组合代码。在我将使用 Dictionary 对象的另一个类中,此 main 中对 Dictionary 对象的调用将采用相同的语法。我必须使用指针,类要求。
-
函数和类声明之间的奇怪混合是什么?这甚至可以编译吗?哪个编译器?此外,您可以很好地重用代码,而无需将其放入类中。 OOP 是一个工具,而不是一个目标!
-
对不起,我不明白你的意思。我对此很陌生,您的意思是参数(const char *)?正在编译。
-
@teamram19 - 你需要实现什么作为指针?您的代码存在内存泄漏。如果您的意思是
main中的那一行,则不需要在main中使用指针——这就是我提到这不是Java 的原因。第二:stackoverflow.com/questions/8365013/… 这是一个两行过程。
标签: c++ string pointers ifstream c-strings