#include <iostream>
#include <string>
#include <sstream>
#include <strstream>
using namespace std;
struct worker
{
char name[40];
int age;
float salary;
};
int main()
{
//C 方法
cout << "C 格式化输入输出演示:" << endl;
//格式化输入
char in_arr[100] = "Jerry 20 6000.8";
struct worker w;
sscanf_s(in_arr, "%s %d %f", w.name, 40, &w.age, &w.salary);
printf("%s, %d, %f\n", w.name, w.age, w.salary);
//格式化输出
char out_arr[100];
w.age = 25;
w.salary = 9000.6;
sprintf_s(out_arr, "%s %d %f", w.name, w.age, w.salary);
printf("%s\n", out_arr);
//C++方法
cout << "C++ 格式化输入输出演示:" << endl;
//格式化输入
string str = "Tom 7 7000.9";
istringstream is(str);
is >> w.name >> w.age >> w.salary;
cout << w.name << " " << w.age << " " << w.salary << endl;
//格式胡输出
ostringstream os;
os << w.name << " " << w.age << " " << w.salary;
cout << os.str() << endl;
//C和C++方法: istrstream和ostrstream操作对象是数组
cout << "C/C++格式化输入输出演示:" << endl;
char arr[] = "Dog 28 10000.9";
istrstream iss(arr);
iss >> w.name >> w.age >> w.salary;
cout << w.name << " " << w.age << " " << w.salary << endl;
char arr1[100];
ostrstream oss(arr1, 100);
oss << w.name << " " << w.age << " " << w.salary;
cout << w.name << " " << w.age << " " << w.salary << endl;
return 0;
}
C++ 如何分别使用C和C++进行格式化输入输出操作
于 2024-05-21 19:49:37 首次发布