String input control: several functions related to the input of spaces and carriage returns

String input control: several functions related to the input of spaces and carriage returns

Usage of cin, cin.getline(), getline()

Main content:
1. Usage of cin 2. Usage
of cin.getline() 3. Usage
of getline()
4. Notice

1. cin>>
Usage 1: Input a number or character

#include <iostream>
using namespace std;
int main ()
{
    
    
	int a,b;
	cin>>a>>b; 
	cout<<a+b<<endl;
}

Usage 2: Receive a character string and end when it encounters "space", "TAB", "enter"

#include <iostream>
using namespace std;
int main ()
{
    
    
	char a[20];
	cin>>a;
	cout<<a<<endl;
}

Input: jkljkljkl
Output: jkljkljkl
Input: jkljkl jkljkl //End with a space
Output: jkljkl

2.
Usage of cin.getline() : Receive a string, can receive blanks and output, read line breaks

#include <iostream>
using namespace std;
int main ()
{
    
    
	char m[20];
	cin.getline(m,5);
	cout<<m<<endl;
}

Input: jkljkljkl Output: jklj
receives 5 characters into m, the last of which is'\0', so only 4 characters are output;

If you change 5 to 20:
input: jkljkljkl
output: jkljkljkl
input: jklf fjlsjf fjsdklf
output: jklf fjlsjf fjsdklf
extension:
1. cin.getline () actually has three parameters, cin.getline (a variable that receives a string, and a character is received Number, end character)
2. When the third parameter is omitted, the system defaults to'\0'
3. If you change the example cin.getline() to cin.getline(m,5,'a'); When input jlkjkljkl, output jklj, when input jkaljkljkl, output jk

3.
Use of getline() : Receive a string, can receive spaces and output, need to include "#include"

#include<iostream>
#include<string>
using namespace std;
int main ()
{
    
    
	string str;
	getline(cin,str);
	cout<<str<<endl;
}

Input: jkljkljkl
Output: jkljkljkl
Input: jkl jfksldfj jklsjfl
Output: jkl jfksldfj jklsjfl

Fourth, note the problem
1. cin.getline() belongs to the istream stream, and getline() belongs to the string stream, which are two different functions.
2. When using cin>> and getline() at the same time, you need to pay attention to: After the cin>> input stream is completed, before getline(), it needs to pass

str="\n";
getline(cin,str);

Use the carriage return character as the input stream cin to clear the cache. If you don’t do this, the getline() input prompt will not appear on the console, but skip it directly, because the program defaults to the previous variable as input flow.

Guess you like

Origin blog.csdn.net/hyl1181/article/details/107487842