typedef basic_istream<char> istream;
输入流对象可以读取和解释来自字符序列的输入。 提供了特定的成员来执行这些输入操作(参见下面的函数)。
标准对象 cin
就是这种类型的对象。
istream& getline (char* s, streamsize n );
istream& getline (char* s, streamsize n, char delim );
从流中提取字符作为未格式化的输入,并将它们作为 c
字符串存储到 s
中,直到提取的字符是定界字符,或者 n
个字符已写入 s
(包括终止的空字符)。
// istream::getline example
#include // std::cin, std::cout
int main () {
char name[256], title[256];
std::cout << "Please, enter your name: ";
std::cin.getline (name,256);
std::cout << "Please, enter your favourite movie: ";
std::cin.getline (title,256);
std::cout << name << "'s favourite movie is " << title;
return 0;
}
Please, enter your name: sjn
Please, enter your favourite movie: op
sjn's favourite movie is op
此示例说明如何从标准输入流 (cin
) 中获取行
typedef basic_ostream<char> ostream;
输出流对象可以写入字符序列并表示其他类型的数据。 提供了特定的成员来执行这些输出操作(参见下面的函数)。
标准对象 cout
、cerr
和 clog
就是这种类型的对象。
arithmetic types (1)
ostream& operator<< (bool val);
ostream& operator<< (short val);
ostream& operator<< (unsigned short val);
ostream& operator<< (int val);
ostream& operator<< (unsigned int val);
ostream& operator<< (long val);
ostream& operator<< (unsigned long val);
ostream& operator<< (float val);
ostream& operator<< (double val);
ostream& operator<< (long double val);
ostream& operator<< (void* val);
stream buffers (2)
ostream& operator<< (streambuf* sb );
manipulators (3)
ostream& operator<< (ostream& (*pf)(ostream&));
ostream& operator<< (ios& (*pf)(ios&));
ostream& operator<< (ios_base& (*pf)(ios_base&));
// example on insertion
#include // std::cout, std::right, std::endl
#include // std::setw
int main() {
int val = 65;
std::cout << std::right; // right-adjusted (manipulator)
std::cout << std::setw(10); // set width (extended manipulator)
std::cout << val << std::endl; // multiple insertions
return 0;
}
输出
65
#include
#include
#include
#include
#include
#include
using namespace std;
void txt_to_vectordouble(vector<float>& res, string pathname)
{
ifstream infile;
infile.open(pathname.data()); //将文件流对象与文件连接起来
assert(infile.is_open()); //若失败,则输出错误消息,并终止程序运行
string s;
while (getline(infile, s)) {
istringstream is(s); //将读出的一行转成数据流进行操作
double d;
while (!is.eof()) {
is >> d;
res.push_back(d);
}
s.clear();
}
infile.close(); //关闭文件输入流
}
int main()
{
vector<float> data;
txt_to_vectordouble(data, "./1.txt");
for (auto a : data) {
cout << a << endl;
}
return 0;
}