【问题标题】:c++ while(getline (file,str)) doesnt workc++ while(getline (file,str)) 不起作用
【发布时间】:2014-12-25 17:56:02
【问题描述】:

我正在尝试从文件中读取以填充二维向量(向量的向量)。

void readFromFile()
    {
        string str;
        ifstream fileToOpen("test.txt");
        if (fileToOpen.is_open())
        {
            resetBoard();
            height=count(istreambuf_iterator<char>(fileToOpen),istreambuf_iterator<char>(), '\n');
            length=height*2-1;
            cout<<board.size()<<endl;
            while(getline(fileToOpen,str))
            {
                cout<<"inside while\n";
                stringstream ss(str);
                int i;
                vector<short unsigned> line;
                while (ss>>i)
                {
                    line.push_back(i);
                }
                board.push_back(line);
            }
            fileToOpen.close();
            //board.shrink_to_fit();
        }
        else
            cout<<"Unable to open file!\n";
        print();

    }

您可以忽略大多数与实际文件打开和读/写向量无关的代码。问题首先是while循环似乎没有执行

    while(getline(fileToOpen,str))
    {
        cout<<"inside while\n";

cout 语句永远不会触发,我只是想不通为什么会这样那一点

我的文本文件

0000000000000001000000000000000
0000000000000011100000000000000
0000000000000110010000000000000
0000000000001101111000000000000
0000000000011001000100000000000
0000000000110111101110000000000
0000000001100100001001000000000
0000000011011110011111100000000
0000000110010001110000010000000
0000001101111011001000111000000
0000011001000010111101100100000
0000110111100110100001011110000
0001100100011100110011010001000
0011011110110011101110011011100
0110010000101110001001110010010
1101111001101001011111001111111

【问题讨论】:

  • 使用流迭代器调用std::count() 后,流中的位置在末尾。使用lengthheight 有什么意义?
  • @0x499602D2 这些变量是全局类变量,在方法外使用

标签: c++ file-io vector getline


【解决方案1】:
height=count(istreambuf_iterator<char>(fileToOpen),istreambuf_iterator<char>(), '\n');

这会耗尽整个文件。所以在那之后,没有更多的行可以阅读。很明显,对 getline 或任何其他输入函数的调用都会失败。

您可以清除流中的错误并将其重置为开头,但为什么您首先需要该行?使用getline 阅读时数行数。或者在你读完之后直接从board.size()获取它(这里我假设board是一个标准的序列容器,并且它预先是空的)。

【讨论】:

  • 那是我一开始就认为我需要在开始时需要几行,但最终不需要它,你永远不会想到这是原因
【解决方案2】:

它位于 height=count(...) 行之后的 eof 处。

在while(getline)前添加:

fileToOpen.seekg(0, fileToOpen.beg);

【讨论】:

  • 请注意,对于文件流,这实际上并不能保证用任何东西重新填充缓冲区。
猜你喜欢
  • 1970-01-01
  • 2019-08-09
  • 2013-10-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多