【问题标题】:C++; Using strings getline() not working with file inputC++;使用字符串 getline() 不适用于文件输入
【发布时间】:2012-08-24 18:08:35
【问题描述】:

我可以让 getline() 与 cin (getline(cin,line)) 一起工作,但是当我打开一个流时,它不会从文件中读取该行。该文件包含元素周期表中的元素列表。

例如:
H

O
等等……

编辑:

但是,当我尝试 cout 新读取的行时,它不会将其放入该行的 var 符号中:
cout

它没有给我任何东西,但它应该返回第一个元素 (H)。

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

using namespace std;

void print(vector <string> x)
{
    cout << "list of elements:" << endl;
    for (int i = 0; i < x.size(); ++i)
    {
        cout << x[i] << endl;
    }
}

int main(int argc, char** argv) 
{
    string symbol;
    vector <string> elementlist;
    ifstream readin;

    readin.open("Elements.txt");
    getline(readin,symbol);
    cout << "symbol: " << symbol << endl;
    while (!readin.good())
    {
        elementlist.push_back(symbol);
        getline(readin,symbol);
    }
    print (elementlist);
    return 0;
}

【问题讨论】:

  • 我在发完帖子之前不小心按了 Enter。我很抱歉。
  • @user1634904 你的循环条件是!readin.good(),最终是false,所以你从来没有真正读过任何东西。反转它。
  • 此外,该行没有被放入 getline 的符号中。那里发生了什么?
  • 指定输入无效。出于某种原因,将它与 cin 一起使用确实有效,只是不尝试获取文件的第一行。嗯嗯
  • @Cerealkiller050 你能分享你正在使用的文件吗?

标签: c++ input iostream getline


【解决方案1】:

我会这样做:

#include <string>
#include <iostream>
#include <fstream>
#include <vector>
#include <iterator>

class line {
    std::string data;
public:
    friend std::istream &operator>>(std::istream &is, line &l) {
        std::getline(is, l.data);
        return is;
    }
    operator std::string() const { return data; }    
};

int main() {
    std::ifstream readin("Elements.txt");

    // Initialize vector from data in stream:
    //
    std::vector<std::string> 
        element_list((std::istream_iterator<line>(readin)),
                      std::istream_iterator<line>());

    // write data from vector to cout:
    //
    std::copy(element_list.begin(), element_list.end(),
             std::ostream_iterator<std::string>(std::cout, "\n"));

    return 0;
}                              

【讨论】:

  • 您不希望std::istream_iterator 可以与自定义分隔符一起使用吗? :-(
  • @veer:是的,有时。使用some effort,它可以。至少为此,line 类更容易。
【解决方案2】:

正如我在my comment 中所说,您的循环条件是错误的。

while (!readin.good())
{
    elementlist.push_back(symbol);
    getline(readin,symbol);
}

事实证明,您想要使用条件readin.good() 进行循环。由于!readin.good() 的计算结果为false,因此您永远不会真正进入循环。

【讨论】:

  • 您通常也想使用while (x.good())。前段时间,我发布了一个blog entry,关于如何执行此操作可能会有所帮助。
  • @JerryCoffin 对。在我最初使用的示例中,我演示了while (std::getline(std::cin, line) &amp;&amp; std::cin.good()) { ... }。这有什么问题吗? PSstd::getline 永远不会短路。
  • 是的,while (std::getline(...)) 通常是做事的好方法。
  • @JerryCoffin 啊,我现在明白了。我忽略了ios::operator void* :-)
猜你喜欢
  • 2012-09-19
  • 2021-04-07
  • 1970-01-01
  • 2017-03-31
  • 2013-06-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多