c++中的各种流
文件输入流ifstream 读数据
#include <iostream>
#include <iostream>
#include <fstream>
int main(int const argc, char const *const *argv)
{
std::ifstream is{"hello.txt"};
if (is.good())
{
std::string s;
while (is >> s)
{
std::cout << s;
std::cout << "\n";
}
is.close();
}
}
结果:
文件输出流 ofstream 写数据
#include <iostream>
#include <fstream>
int main(int const argc, char const *const *argv)
{
/**
* if not exist
* create new file
* else
* overwrite
*/
// outputstream write something
std::ofstream os{"hello.txt"};
if (os.good())
{
os << "hello ofstream";
os << "i love coding";
os.close();
}
}
结果:
字符输入符流
字符输出流
从cin错误中恢复
使用方法cin.clear(); cin.ignore()
#include <iostream>
#include <fstream>
#include <limits>
using namespace std;
void reset_cin()
{
// clear all error status bits
cin.clear();
// clear input buffer
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
int main()
{
cout << "i? ";
int i = 0;
cin >> i; // ← 1st
if (cin.fail())
reset_cin();
cout << "j? ";
int j = 0;
cin >> j; // ← 2nd
cout << "i: " << i << ", "
<< "j: " << j << '\n';
}
命令行参数
程序运行时附带的参数
main.cpp代码如下(功能是控制台打印传入的参数):
#include <iostream>
int main (int const argc, char const*const* argv) {
for (int i = 0; i < argc; ++i) {
std::cout << argv[i] << '\n';
}
}
在ubantu环境下,编译运行:
g++ main.cpp -o main
./main 12 abc 3x996
结果如下: