Here I’m going to summarize some common techniques for IO, especially for type conversion and spliting the string, which are usually the most annoying parts in IO.
Read a file
1 |
|
Note: getline
sets the ios::fail when count-1
characters have been extracted. So, before reseting the read pointer fin.clear()
must be called.
Converting the type
String to int
1 |
|
String to char array
Approach 1:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
using namespace std;
int main(){
string str = "fuck";
int n = str.length();
char char_array[n+1];
strcpy(char_array, str.c_str());
for(int i = 0; i < 0; i++)
cout << char_array[i] << endl;
return 0;
}Note: The
c_str()
function is used to return a pointer to an array that contains a null terminated sequence of character representing the current value of the string. So the length ofstr.c_str()
isstr.length()+1
.Approach2:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
using namespace std;
int main(){
string str = "fuck";
char char_array[str.length()];
for(int i = 0; i < 0; i++){
char_array[i] = str[i];
cout << char_array[i] << endl;
}
return 0;
}
char array to int array(by letter)
1 |
|
Note: If we want the length of an int array, we need use sizeof(int_arr)/sizeof(int)
.
char array to int array(by word)
1 |
|
Split the string
Parse a comma-delimited string into int array.
1 |
|
Parse a comma-delimited string into string array.
1 |
|