逐字读取输入文件

时间:2014-07-31 05:41:50

标签: c++ function file-io

我首先要说的是,这是一项家庭作业,但我的老师对如何做事真的不太清楚。

我被要求在c ++中编写一个函数,它将一次传递一个文件中的单词。该函数将计算字长,然后在其自己的行上打印出TO SCREEN字及其长度。

main将打开您的输入文件,在循环中逐字读取,然后将该单词传递给您的函数以便打印。

我知道如何使用fstream和所有这些来打开文件,逐字逐句读取,但不能通过void readfile()读取循环或函数。我的问题是把所有东西放在一起。

这是我打开文件,获取长度并以并行数组显示它的程序

//declare parallel arrays

string words [MAXSIZE];

//open files
outputFile.open("output.txt");
inputFile.open ("/Users/cathiedeane/Documents/CIS 22A/Lab 4/Lab 4 Part 2/lab4.txt");


//inputvalidation

while (!inputFile.eof())
{
    for(int i = 0; i < MAXSIZE; ++i)
    {

        outputFile << words[i] << " " << endl;
        inputFile >> words[i];

    }
    inputFile.close();

}
for (int i= 0; i <= MAXSIZE; i++)

{   cout << words[i] << ":" << words[i].size()<< endl;
    outputFile << endl;
}

//close outputfile
outputFile.close();
return 0;
}

4 个答案:

答案 0 :(得分:0)

所以基本上你的任务是:

function read_word
  /* what you have to work on */
end

function read_file_word_by_word
  open file
  while not end_of_file
    word = read_word
    print word, word_length
  end
  close file
end

要阅读单词,您需要定义它是什么。通常它是一堆字母,由其他不是字母的字符(空格,逗号等)分隔。

您可以逐个字符地阅读文件,并在它们是字母时存储它们,直到您遇到其他类型的字符。你存储的是一个单词,你可以很容易地得到它的长度。

提示:http://www.cplusplus.com/reference/istream/istream/get/允许您从文件中读取单个字符。

答案 1 :(得分:0)

#include <fstream>
#include <iostream>
#include <string>

using namespace std;

void func(const string& word)
{
    //set field width
    cout.width(30);
    cout << left << word << " " << word.size() << endl;
}

int main(int argc, char* argv[])
{
    ifstream ifs("F:\\tmp\\test.txt");
    if(ifs.fail())
    {
        cout << "fail to open file" << endl;
        return -1;
    }

    _Ctypevec ct =  _Getctype();
    for(char ch = 0; ch < SCHAR_MAX; ch++)
    {
        //set all punctuations as field separator of extraction
        if(ispunct(ch))
        {
            (const_cast<short*>(ct._Table))[ch] = ctype<char>::space;
        }
    }

    //change the default locale object of ifstream
    ifs.imbue(locale(ifs.getloc(), new ctype<char>(ct._Table)));

    string word;
    while(ifs >> word)
    {
        func(word);
    }

    ifs.close();
}

答案 2 :(得分:0)

既然你提出问题已经过了一段时间了,我想补充一点,这可以用很少的代码来解答:

#include <iostream>
#include <string>
#include <fstream>
using namespace std;

void printString( const string & str ) { // ignore the & for now, you'll get to it later.
    cout << str << " : " << str.size() << endl;
}

int main() {
    ifstream fin("your-file-name.txt"); 

    if (!fin) {
       cout << "Could not open file" << endl;
       return 1;
    }

    string word; // You only need one word at a time.
    while( fin >> word ) {
       printString(word);
    }

    fin.close();
}

关于fin >> word的一个小注释,只要有一个单词读入字符串,该表达式就返回true。默认情况下,它也会跳过任何空格(制表符,空格和换行符)。

答案 3 :(得分:0)

您显然希望将每个单词分隔到其自己的string索引中,以将它们存储在您的数组中。要分隔每个单词,请建立一个断点,如char break = ' ';然后,当您的IOStream正在读取文件时,只需使用迭代器(i ++)将单词添加到索引

相关问题