逐字读取文本文件时如何忽略"end of line"或"new line"字符?

How can I ignore the "end of line" or "new line" character when reading text files word by word?

本文关键字:line end of new 字符 何忽略 读取 取文本 文件      更新时间:2023-10-16

目标:

我正在逐字读取文本文件,并将每个单词保存为数组中的元素。然后我逐字打印出这个数组。我知道这可以更有效地完成,但这是为了一个任务,我必须使用数组。

我正在对数组做更多的事情,例如计算重复的元素、删除某些元素等。我还成功地将文件转换为完全小写且没有标点符号。

现状:

我有一个文本文件,如下所示:

beginning of file


more lines with some bizzare     spacing
some lines next to each other
while
others are farther apart
eof
<小时 />

这是我的一些代码,itemsInArray0初始化,并引用为wordArray[ (approriate length for my file ) ]的单词数组:

<小时 />
ifstream infile;
infile.open(fileExample);
while (!infile.eof()) {
    string temp;
    getline(infile,temp,' ');  // Successfully reads words seperated by a single space
    
    
    if ((temp != "") && (temp != 'n') && (temp != " ") && (temp != "n") && (temp != "") {
            wordArray[itemsInArray] = temp;
            itemsInArray++;
    }
<小时 />

问题:

我的代码将行尾字符保存为数组中的项目。在我的if语句中,我列出了我试图区分行尾字符的所有方法,但我没有运气。

如何防止行尾字符保存为数组中的项目?

我已经尝试了在类似这样的线程上找到的其他一些方法,包括一些我无法工作的*const char方法,以及迭代和删除新行字符。我已经为此工作了几个小时,我不想重新发布相同的问题,并且尝试了很多方法。

std::string 的标准>>运算符重载已经使用空格作为字边界,因此您的程序可以大大简化。

#include <iostream>
#include <string>
#include <vector>
int
main()
{
  std::vector<std::string> words {};
  {
    std::string tmp {};
    while (std::cin >> tmp)
      words.push_back(tmp);
  }
  for (const auto& word : words)
    std::cout << "'" << word << "'" << std::endl;
}

对于您正在显示的输入,这将输出:

'beginning'
'of'
'file'
'more'
'lines'
'with'
'some'
'bizzare'
'spacing'
'some'
'lines'
'next'
'to'
'each'
'other'
'while'
'others'
'are'
'farther'
'apart'
'eof'

这不是你想要的吗?

流的提取运算符应该为您处理这个问题

std::ifstream ifs("file.txt");
while (ifs.good())
{
    std::string word;
    ifs >> word;
    if (ifs.eof())
    {
        break;
    }
    std::cout << word << "n";
}
int main()
{  
    char *n;
    int count=0,count1=0;
    ofstream output("user.txt");
    output<<"aa bb cc";
    output.close();
    ifstream input("user.txt");
    while(!input.eof())
    {
        count++;
        if(count1<count)
        cout<<" ";
        count1=count;
        input>>n;
        cout<<n;
    }
    cout<<"ncount="<<count;
    getch();
}
相关文章: