Input problem with space string in C++ solved

  • 2020-05-17 06:07:02
  • OfStack

preface

String 1 is a straight point and difficult, a lot of written interviews will be involved, with the space of the string is 10 points common, now to the string input question 1 under the summary.

C++ ignores characters after the space when entering cin, for example


char a[100];

cin>>a; 

C++ when using cin input will ignore the characters after the space, enter "hello world" output is "hello";

So if I'm looping in


for(int i=0;i<100;i++)

{

cin>>a[i];

} 

Do I enter 100 Numbers like that? Or define 1 n, know in advance how long the character is, and make i < n, not a very good method.

You can use it here cin.getline(a,100); Instead, this function is the default input carriage return to indicate the end of the input.

Below is an example: input hello world, output dlrow olleh, refer to the answer


#include<iostream>

using namespace std;

int main()

{

 char a[20];

 for(int i=0;i<20;i++)

 { a[i]='\0';}

  cin.getline(a,20);

 // cin>>a;

 cout << a<<endl;

 for(i=sizeof(a)-1;i>=0;i--)

 {

  if(a[i]!='\0')

  cout<<a[i];

 }

 return 0;

} 

conclusion


Related articles: