I/O Stream 应试向整理

I/O stream integration

stdin stream

deal with separately in a cpp form

1
2
3
4
5
6
7
string temp;
while(cin>>temp){
cout<<temp<<" ";
if (getchar()=='\n')
break;
}
cout<<endl;

deal with altogether

1
2
3
4
5
6
7
string s;
int i=1;
while(getline(cin,s)){
cout<<i<<" "<<s<<"\n";
i++;
}
return 0;

input from file

C-style method

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
void P4(){
FILE *fp = fopen("P4.txt", "r");
FILE *output = fopen("P4_encrypt.txt", "w+");
char temp{};
while (1){
temp = fgetc(fp);
if (feof(fp)) break;
if (temp == '.') fprintf(output, "%c", '?');
else if (temp == '?') fprintf(output, "%c", '.');
else if (temp == ' ') fprintf(output, "%c", '&');
else if ((temp <= 'z' && temp >= 'a') || (temp <= '9' && temp >= '0'))
fprintf(output, "%c", temp - 1);
else fprintf(output, "%c", temp);
}
fclose(fp);
fclose(output);
}

include<fstream>(if not required to deal with elements separately)

1
2
3
4
5
6
7
8
9
10
11
int main() {
ifstream in("class.cpp");
ofstream out("withNumber.cpp");
string s{};
int i=1;
while(getline(in,s)){
out<<i<<" "<<s<<"\n";
i++;
}
return 0;
}

include<fstream>(but required to deal with elements separately with xs branket)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
using namespace std;
int main(){
string line;
ifstream in("p3.txt");
while (getline(in, line)){
vector<int> numbers;
int i, sum = 0;
istringstream get(line);
while (get >> i) numbers.push_back(i);
for (auto number : numbers) sum += number;
cout << sum << endl;
}
return 0;
}

an inefficient way of C-style(if required to deal with elements separately with xs branket)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
FILE *fp = fopen("P3.txt", "r");
char temp[256];
while (getline(fp,temp)){
while (temp[0] == ' ')
for (int i = 1; i < 256; i++)
temp[i - 1] = temp[i];
for (int i = 5; i > 0; i--)
if (temp[i] == '\0' && temp[i - 1] == ' ')
temp[i - 1] = '\0';
for (int i = 1; i < 255; i++){
if (temp[i] == ' ' && temp[i + 1] == ' '){
for (int j = i + 1; j < 256; j++)
temp[j] = temp[j + 1];
i--;
}
}
int result = 0;
int intTemp = 0;
while (sscanf(temp, "%i", &intTemp)){
result += intTemp;
while (temp[0] != ' ' && temp[0] != '\n' && temp[0] != '\0')
for (int i = 1; i < 256; i++)
temp[i - 1] = temp[i];
char car{};
sscanf(temp, "%c", &car);
if (car == '\0' || car == '\n') break;
for (int i = 1; i < 256; i++) temp[i - 1] = temp[i];
}
cout << result << endl;
}

I/O Stream 应试向整理
https://cloudflipper.github.io/2022/12/12/iostream-integration/
创作于
2022年12月12日
更新于
2026年3月15日