# C語言輸入輸出
## 字符輸入輸出
* getchar / putchar
* scanf / printf
```
scanf("%c",&c); //將數據放入變量需要 & 取地址符
```
```
// scanf 與 printf 的應用
#include <iostream>
using namespace std;
int main()
{
float x; int n;
pritnf("input:");
scanf("%f%d", &x, &n);
printf("%f%d", x, n);
putchar('\n');
return 0;
}
```
```
#include <iostream>
using namespace std;
int main()
{
int n;
n = 1000;
//printf("%f",n); 數據類型不匹配!
printf("%f", 1.0*n); //不同進制%x %o
printf("%-10d",n);
putchar('\n');
/*雙精度數據
double n;
n = 1.23456789;
printf("%.2f",n); //%.2f取小數點后兩位
printf("%e",n); //指數形式
putchar('\n');
*/
return 0;
}
```
#### printf 就講到這里,不用死記硬背,在用中學習記憶
* 說明: & 是取地址運算符,scanf 的格式控制串里不要加多余的空格或'\n'
# C++語言輸入輸出
* cin / cout 標準輸入輸出流
```
#include <iostream>
using namespace std;
int main()
{
char c;
cin >> c;
cout << (char) (c - 32) << end; //由于涉及算數運算,輸出時要將數據類型轉換為 char
/*
char c1, c2;
cin >> c1 >> c2;
cout << (char)(c1 - 32) << (char)(c2 - 32) << endl;
*/
/*
char c1; int c2;
cin >> c1;
cin >> c2;
cout << c1 << c2; //數據輸入輸出類型要一致
*/
return 0;
}
```
* cout 格式控制
* setw() / setiosflags(ios::left) / setfill() / setprecision()
```
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
cout << setw(8) << 'a' //預留 8 個字符位置
<< setw(8) << 'b' << endl;
/* setiosflags() 和 setfill() 的效果
cout << setiosflags(ios::left) //靠左
<< setfill('*') //填充空白字符為“*”
<< setw(8) << 'a'
<< setw(8) << 'b' << endl;
*/
/*設置浮點數精度 setprecision()
double f = 17 / 7.0;
cout << setiosflags(ios::fixed) //設置顯示類型
<< setprecision(3) << f << endl;
*/
return 0;
}
```
* string 處理字符串
* string 不是基本數據類型
```
#include <string> //不要忘
```
```
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str1; //定義 string 對象
string str2("Hello"); //定義并初始化
string str3 = str2; //定義并初始化
/* string 的輸入輸出
string str1, str2;
str1 = "123", str2 = "abc";
str3 = str1 + str2;
//cin >> str1 >> str2;
cout << str1 << ' ' << str2;
*/
return 0;
}
```
* 文件的輸入輸出
* fstream 文件流對象
```
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
/* idata.txt 內容
1
2
3
4
5
6
7
8
9
10
*/
ifstream ifile("idata.txt");
int sum = 0, value;
cout << "data:";
while(ifile >> value) //只要還有數據未讀完就一直循環
{
cout << value << " ";
sum += value;
}
cout << endl;
cout << "sum is:" << sum << endl;
return 0;
}
```