【问题标题】:How can I ignore the "end of line" or "new line" character when reading text files word by word?逐字阅读文本文件时如何忽略“行尾”或“换行”字符?
【发布时间】:2015-03-31 07:13:47
【问题描述】:

目标:

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

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

现状:

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

beginning of file




more lines with some bizzare     spacing
some lines next to each other
while

others are farther apart
eof

这是我的一些代码,其中 itemsInArray 初始化为 0 和一个称为 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 != "\0") {
            wordArray[itemsInArray] = temp;
            itemsInArray++;
    }

问题:

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

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

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

【问题讨论】:

  • 此时,我的 .txt 文件包含一整本书,没有大写字母。有几个“返回”或新行来分隔章节。我已经绕过将额外的空格保存为我的数组中的项目,我只是在努力 not 保存换行符。再次感谢您。

标签: c++ arrays getline end-of-line


【解决方案1】:

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'

这不是你想要的吗?

【讨论】:

    【解决方案2】:

    流的提取操作符应该为您处理好这些

    std::ifstream ifs("file.txt");
    while (ifs.good())
    {
        std::string word;
        ifs >> word;
        if (ifs.eof())
        {
            break;
        }
    
        std::cout << word << "\n";
    }
    

    【讨论】:

    • 非常感谢。这有帮助。我是编码新手,不知道中断功能。我遇到的一个问题是,有时一个返回(新行)或多个返回会作为它自己的字符串读入。
    【解决方案3】:
    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();
    }
    

    【讨论】:

    • 这只是为了避免间距。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-04
    相关资源
    最近更新 更多