Use string along with other data type

Can string not be used along with other data types.
for example
int main() {
int a=4;
string s="hello ";

int b;
cin>>b;

int sum=a+b;
cout<<sum<<endl;

string c;
getline(cin,c);

string p = s+c;
cout<<p<<endl;

}

when I comment the int data types then the string result shows but with int type addition in program string didn’t show the expected output

@Ajitverma1503
String can work with other data types and we use it very often with other data types.
The problem with your code is not actually with int or any other data type but rather with the input.
getline( ) is the actual problem.
There are several ways to take input for strings , each having its own perks and drawbacks. The problem with getline( ) is that it causes several problems with buffer.
I suggest you to remove the getline( ) statement for once and use
cin >> c;
in place of it and you will find that your problem is solved.

Using cin will only allow you to take a single word as input though , as I said , each method has its own perks and drawbacks.
If you wish to take input till new line character ( as I can guess that this was the reason why you used getline( ) in the first place ) , you need to clear the buffer first.
Write
cin.ignore( );
before getline(cin,c) ; statement.

cin.ignore( ); commands the compiler to empty the buffer so that we can get proper input using getline( ).

Try these variations and let me know if you have any further doubts.

1 Like

Thanks for explaining a new concept :relaxed:

How can we know about the perks and drawbacks of getline(),cin,and other inbuilt commands.

@Ajitverma1503
There are only a few methods so I simply tried all of them together with different variations and examples. That’s the best way to go about it. You can also refer to their documentation on the internet or look out for examples.
There’s really not one source where you can encounter details about all of them.
Just make up examples and try them out yourself. If you face any problems or difficulties , we are here to help you out.

1 Like