【发布时间】: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