C++中的一些常用输入输出:
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
using namespace std;
void win_io() //由控制台输入
{
string line;
cout << "输入一些字符后Enter:";
//cin >> line;
getline(cin, line); //输入可以带有空格
cout << "从控制窗口读取的内容:" << line << endl;
}
void file_io() // 文件进行输入
{
ifstream in_file("test.txt");
string line;
while(getline(in_file, line))
{
cout << line << endl;
}
in_file.close();
}
void file_io_2()
{
fstream in_file("test.txt", ios_base::in | ios_base::out);
const int MAX_LEN = 100;
char line[MAX_LEN];
while(in_file.getline(line, MAX_LEN))//也可使用infilne >> line
//while(in_file >> line)
{
cout << line << endl;
}
in_file.close();
in_file.open("test.txt", ios_base::out);
//in_file.seekg(ios::end);
in_file << "nihao\n";
in_file.close();
}
void buf_io() //由缓冲区进行输入
{
istringstream ss("hello world");
ostringstream oss;
string word;
while(ss >> word)
{
cout << word << endl;
oss << word << endl;
}
cout << "oss " << oss.str();
}
void buf_io_2()
{
stringstream ss;
ss << "hello world";
string word;
while(ss >> word)
{
cout << word << endl;
}
}
void StringToInt(string str, int& i)//使用sstream实现类型转换同一个sstream对象类型转换时记得清空(.clear())
{
stringstream ss;
ss << str;
ss >> i;
}
int main()
{
win_io();
//file_io();
file_io_2();
buf_io();
//buf_io_2();
string str("123");
int i;
StringToInt(str, i);
cout << i << endl;
system("pause");
return 0;
}
扩展: http://www.cnblogs.com/azraelly/archive/2012/04/14/2446914.html