【发布时间】:2017-10-01 22:28:03
【问题描述】:
我是一名学生,我正在尝试制作一个刽子手程序。我得到了一个名为 words.dat 的文件,我应该将其用于我的刽子手程序,但我不知道如何存储数据并将其放入字符串数组中。我正在尝试创建一个专用于导入文件的函数。我不知道 dat 文件中会有多少单词,但我的老师说最多有 100 个。这是我对如何做的粗略猜测,但我在尝试编译它时只会遇到很多错误。如何将 dat 文件中的单词放入字符串数组中?
words.dat
COW
SCHOOL
KEY
COMPUTER
到目前为止我的功能
#include <string>
#include <fsteam>
using namespace std;
bool initializeFile(string filename){
int importWord = 0;
string words[100];
ifstream input;
input.open(filename, 'r');
if(input.fails){
return false;
}
/*
Tring to make for loop that runs through
all the characters in input(dat file) and
store them into the words array. if the character isn't a letter it
skips it and continues to the next row
*/
for(int i=0;i< input.length();i++){
if(input[i] =="\n"){
importWord++;
}
if(input[i] != "\n"){
words[importWord]=input[i];
}
}
return true;
}
【问题讨论】:
-
您熟悉
std::vector类型吗?这可能是比原始 C++ 数组更好的工具。 -
您可能应该找到一些关于 C++ 中文件和读取文件的教程,因为
std::ifstream及其任何基础都没有length成员函数,或者像这样使用它来读取它。也许甚至get a couple of good beginners books 来阅读? -
您可能有兴趣了解
std::getline函数? -
不,我不熟悉 std::vector
标签: c++