逐字逐句地读取输入文件

Read input file word by word

本文关键字:文件 输入 读取 逐字逐句      更新时间:2023-10-16

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

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

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;
}

所以基本上你的任务是:

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/允许您从文件中读取单个字符。

#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();
}

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

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

#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。默认情况下,它还会跳过任何空白(制表符、空格和换行符(。