How to read a line of string with spaces after C++14

Previous article:
In the C++11 standard and before, you can still use the getsread, but C++14 officially deletes getsthis 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'
getlinefor 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 getinvalidate 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 getreading is completed, use it again getto manually filter out the line breaks:
cin.get(str, 100).get();


C、scanf("%[^\n]", str)

And getthe 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 scanfthem be followed by a getcharfilter newline character.


D、fgets(str, size, stdin)

In order to solve getsthe read-in security problem, fgetsthe maximum length of the read-in is added size, but a fgetsnewline 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, stringclass

A、getline(std::cin, s)

#include<iostream>
#include<string>
int main()
{
    
    
	std::string s;
	getline(std::cin, s);
	std::cout << s << "\n";
	return 0;
}

Guess you like

Origin blog.csdn.net/weixin_43900869/article/details/114308096