【问题标题】:read file and store into a string array读取文件并存储到字符串数组中
【发布时间】: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;
}

【问题讨论】:

标签: c++


【解决方案1】:

由于每行一个单词,您可以使用std::getline 读取单词。

const int MAXIMUM_WORDS = 100;
std::string words[MAXIMUM_WORDS];
std::string word_from_file = 0;
int word_count = 0;
while (std::getline(word_file, word_from_file))
{
  if (word_count > MAXIMUM_WORDS)
  {
    break;
  }
  words[word_count] = word_from_file;
  ++word_count;
}

如果你已经覆盖了break 语句,你可以使用乘法条件:

while ((word_count < MAXIMUM_WORDS) && (std::getline(word_file, word_from_file))

以上代码足够小,您可以将代码放入您的main 函数中,这样就省去了将数组传递给输入函数的麻烦。

【讨论】:

    猜你喜欢
    • 2012-08-18
    • 1970-01-01
    • 2021-10-25
    • 1970-01-01
    • 1970-01-01
    • 2017-09-29
    • 1970-01-01
    • 2017-11-04
    • 1970-01-01
    相关资源
    最近更新 更多