从文本文件读取时,如何知道是否已到达新行?
When Reading from a Text File, how do I know if I've reached a new line?
给定一个看起来像这样的文本文件:
-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";
相关文章:
- 使用新行和不使用新行读取文件
- 遇到新行时,有没有办法停止istream_iterator
- PangoLayout 中忽略的新行
- 向量是否存在行主要形式?
- 使用 clang 格式时,当行很大时,如何将右括号分成新行?
- 如何检测将文本文件读入 int 数组的新行
- 当 getline 直到新行才读取时会发生什么?
- 添加新行时工作代码引发异常.调试技巧?
- QTree查看新行,没有布局就不可见已更改
- 新行上的 clang 格式右括号
- C++流:保存到新行而不是覆盖旧行
- (C++) 使用诅咒打印从文件中读入的新行
- 按升序输出整数时,将最后一个整数放在新行上
- 用C++计算输入文本的新行数
- 为什么我的代码在终端中没有输出任何内容.开始新行没有错误
- WriteConsoleOutputCharacterW - 我的新行在哪里?
- 为什么当测试用例数为 1 时,我的程序不输入而是打印新行?
- 如何运行 while 循环直到到达新行?
- 从文本文件读取时,如何知道是否已到达新行?
- 如何查看字符是否等于新行