所以我有txt文件,input.txt,我正在阅读我的程序。我能够使用getline
函数获取第一行数字,现在我正在尝试获取每个数字。我将这些数字放入BST,但我不关心这部分,只关注如何得到每个数字。从我可以收集的内容中我需要使用stringstream,但我仍然坚持如何提取每个数字并能够单独添加它们。
BST.cpp
#include "stdafx.h"
#include "BST.h"
#include <iostream>
#include <cstddef>
#include <string>
#include <fstream>
#include <sstream>
using namespace std;
int main()
{
BST<int> B;
fstream input;
input.open("input.txt", ios::in);
string number;
stringstream ss;
if(input.fail())
cout << "File was not opened successfully" << endl;
else
cout<< "File was opened succesffuly" << endl;
getline(input,number,'\n');
cout << number << endl;
ss << number;
return 0;
}
input.txt中
12 6 9 45 3 7 10 2 4 13
4
9
55 18 3 6 78 9
13
66
808 707 909 1001 505 1200 499 644 1190 1592
707
78
答案 0 :(得分:0)
像这样:
std::string line;
int line_number = 1;
while (std:getline(input, line))
{
std::cout << "Line #" << line_number++ << ':';
std::istringstream os(line);
int number;
while (os >> number)
std::cout << ' ' << number;
std::cout << '\n';
}
对于输入的前三行,应该打印
Line #1: 12 6 9 45 3 7 10 2 4 13 Line #2: 4 Line #3: 9