从文本文件读取时,如何知道是否已到达新行?

When Reading from a Text File, how do I know if I've reached a new line?

本文关键字:是否 新行 何知道 文件 文本 读取      更新时间:2023-10-16

给定一个看起来像这样的文本文件:

-1015 -50 -60 70 -30

0 1

1 2

1 3

3 4

4 5

"-1015 -50 -60 70 -30"的第一行应该放在一个数组中。

其余的线应该用作邻接矩阵的连接点。

我怎么知道我是否已到达线路的末尾? 这是我到目前为止的代码。

string temp;
while (getline(txtfile, temp, 'n')) {
istringstream ss(temp);
int num;
while (ss >> num) {
cout << num << endl;
}
}

我可以分隔所有数字,但我想在到达一行末尾后停止。

编辑的代码:

ifstream txtfile("smallgraph.txt");
if (txtfile.is_open()) {
cout << "Successfully opened file " << "graph.txt" << endl;
int nodes = 0;
int budget = 0;
txtfile >> nodes >> budget;
cout << nodes << " " << budget << endl;
vector<int> firstLine;
string temp;
if (getline(txtfile, temp, 'n')) {
istringstream ss(temp);
int num;
while (ss >> num)
firstLine.push_back(num);
}
for (int i = 0; i < firstLine.size(); i++) {
cout << firstLine[i] << " ";
}
}

您的代码将读取文件中的所有数字,并将它们分别打印在单独的行上。 如果只需要小的修改来做你想做的事情:只需将第一行中提取的数字放入向量中,那么你就可以从文件中读取对,并对它们执行邻接矩阵代码需要的任何操作。

std::vector<int> from_first_line;
string temp;
if (getline(txtfile, temp, 'n')) {
istringstream ss(temp);
int num;
while (ss >> num)
from_first_line.push_back(num);
int first, second;
while (txtfile >> first >> second) {
// use for adjacency matrix...
}
}
else
std::cerr << "file contained no entries for vectorn";