C++ reads a string with a space

  • 2020-06-07 04:58:26
  • OfStack

Collate notes on the input of strings in C++

1. cin

cin is the most commonly used input statement in C++, which stops when a space or enter key is encountered

Such as:


#include <iostream>
#include <string>
using namespace std;
int main()
{
   chara[50];
   cin>>a; 
   cout<<a<<endl;
   return0;
}

Input: abcd Hit enter output abcd

Cons: You can only enter strings without Spaces, and when the input contains Spaces, you can only print characters before Spaces

Input: I love China Input space input does not stop, in case of enter input stop, output I, the space after the output is not.

2. gets()

Can read infinitely, end with carriage return, C language function, run in C++ will produce bug.

Such as:


#include <iostream>
#include <cstdio>
using namespace std;
int main()
{
   chara[50];
   cin>>a;
   gets(a);
   cout<<a<<endl;
   return0;
}

Enter I love China Enter ends the input and outputs love China. The first character is automatically discarded.

3. getline()

If you define a variable of type string, consider the getline() function. Usage:


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

Input: I love China Enter does not end the input, it takes two enter to end the input, output: I love China.

4.cin.get cin.getline

The cin. get() function can receive a space to end input in case of a carriage return.


#include <iostream>
using namespace std;
int main()
{
   chara[50];
   cin.get(a,50);
   cout<<a<<endl;
   return0;
}

Input: I love China Enter ends input, output: I love China.

5. cin.getline

The cin. getline() function can be similar to the cin. get() function, or it can receive Spaces to end input in case of a carriage return.


#include <iostream>
using namespace std;
int main()
{
   chara[50];
   cin.getline(a,50);
   cout<<a<<endl;
   return0;
}

Input: I love China Enter ends the input and output is I love China.


Related articles: