-1

I am making something where you have to put your name but my string doesn't save the spaces, why?

#include <iostream>
using namespace std;
string name;
int main()
{
  cout<<"<System>: Please enter your name"<<endl;
  cin>>name;
  cout<<name;
return 0;
}

I entered:

Test 123

And I got:

Test

c4k3ss
  • 23
  • 5
  • 4
    `cin>>name;` reads only until the next space. That's just how it is defined to work. [Reference](https://en.cppreference.com/w/cpp/io/basic_istream/operator_gtgt2). – Lukas-T Mar 12 '21 at 12:19
  • 1
    Does this answer your question? [How to read a complete line from the user using cin?](https://stackoverflow.com/questions/5455802/how-to-read-a-complete-line-from-the-user-using-cin) – TruthSeeker Mar 12 '21 at 12:21

3 Answers3

5

the insertion operator inserts only the first string (before any whitespace) from std::cin to the string if you want to take the whole line use std::getline()

#include <iostream>
using namespace std;
string name;
int main()
{
  cout<<"<System>: Please enter your name"<<endl;
  std::getline(std::cin, name);
  cout<<name;
return 0;
}

And see this Why is "using namespace std;" considered bad practice?

asmmo
  • 6,922
  • 1
  • 11
  • 25
1

std::cin << only reads up to the next space (ie. space, tabulation or line break). If you want to read the whole line, you will have to use std::getline. Moreover, unless you have a very clear reason, you should declare the variable name as a local variable of the function main.

#include <iostream>
using namespace std;
int main()
{
  string name;
  cout<<"<System>: Please enter your name"<<endl;
  getline(cin, name);
  cout<<name;
  return 0;
}
永劫回帰
  • 652
  • 10
  • 21
0

cin takes any whitespace (spaces, tabs, etc.) as a terminating character which is why you're only getting the first word.

Using getline() you can get the whole sentence until the return key is pressed:

int main()
{
    cout<<"<System>: Please enter your name"<<endl;
    getline(cin, name);
    cout<<name;
    return 0;
}
askman
  • 447
  • 4
  • 14