Previous article:
In the C++11 standard and before, you can still use the gets
read, but C++14 officially deletes gets
this unsafe read. Because the read-in automatically ignores spaces, other read-in functions are needed to process strings with spaces.
Specific reading method:
One, character array
A、std::cin.getline(str, size)
#include<iostream>
int main() {
char str[100];
std::cin.getline(str, 100);
std::cout << str << "\n";
return 0;
}
Means you can start from index 0 00 starts to read at most99 999 9 characters, the last one is reserved'\0'
getline
for line breaks, it will stop reading and filter out line breaks.
B、std::cin.get(str, size)
#include<iostream>
int main() {
char str[100];
std::cin.get(str, 100);
std::cout << str << "\n";
return 0;
}
Note:
cin.get()
and cin.get(str, size)
cin.get()
can be read into any character
cin.get(str, size)
not filter wrap that reads a line break is over, and line breaks will still be lost in the buffer.
In the following program, a newline character staying in the buffer will get
invalidate all the following readings.
#include<iostream>
#include<cstring>
using namespace std;
int main()
{
char s1[10], s2[10], s3[10];
cin.get(s1, 10);
cin.get(s2, 10);
cin.get(s3, 10);
cout << strlen(s1) << " : "<< s1 << "\n";
cout << strlen(s2) << " : "<< s2 << "\n";
cout << strlen(s3) << " : "<< s3 << "\n";
return 0;
}
Output:
100
3 : 100
0 :
0 :
Solution: After the get
reading is completed, use it again get
to manually filter out the line breaks:
cin.get(str, 100).get();
C、scanf("%[^\n]", str)
And get
the like, does not wrap the filter: the specific operation is as follows.
#include<cstdio>
int main()
{
char str[100];
scanf("%[^\n]", str); getchar();
printf("%s\n", str);
return 0;
}
In order to ensure that there are no similar errors, it is recommended that all of scanf
them be followed by a getchar
filter newline character.
D、fgets(str, size, stdin)
In order to solve gets
the read-in security problem, fgets
the maximum length of the read-in is added size
, but a fgets
newline character will be read. as follows:
#include<cstdio>
#include<cstring>
using namespace std;
int main()
{
char str[10];
fgets(str, 10, stdin);
for(int i = 0; i < strlen(str); ++i) {
if(str[i] == '\n') printf("x");
else printf("%c", str[i]);
}
return 0;
}
operation result:
input:
123
output:
123x
So if you don't need a newline character, you can str[strlen(str)-1]='\0'
remove the newline character.
Two, string
class
A、getline(std::cin, s)
#include<iostream>
#include<string>
int main()
{
std::string s;
getline(std::cin, s);
std::cout << s << "\n";
return 0;
}