-1
int main(){

    char str1[MAX], str2[MAX];
    cout <<" 1st string: ";
    cin.get(str1, MAX);
    cout <<" 2nd string";
    cin.get(str2, MAX);
    cout << str1 << str2;
    return 0;
}

I am trying to input a string with spaces included in both arrays str1 and str2. The problem is program terminates after taking the first input.

On the output screen:

1st string : abc def

Now when I press enter to take input for 2nd array but then the code terminates and first string is displayed.

Output: 2nd string

abc def

How can I properly use this cin.get() function to take 2 different inputs? Is there any other way to take string with blank spaces for char array ?

MedMekss
  • 349
  • 2
  • 15

3 Answers3

0
std::string _str;
std::getline (std::cin, _str); 
// std::getline (std::cin, _str, _char); 
// if you wish to accept input until first appearance of _char
hivemind
  • 1
  • 4
  • While this answer is probably correct and useful, it is preferred if you include some explanation along with it to explain how it helps to solve the problem. This becomes especially useful in the future, if there is a change (possibly unrelated) that causes it to stop working and users need to understand how it once worked. – Erty Seidohl May 16 '18 at 14:18
0

function getline() handles input that contains embedded blanks or multiple lines.

#include <iostream>
#include <string> //for string class
using namespace std;
int main()
{ //objects of string class
string full_name, address;
getline(cin, full_name); //reads embedded blanks
cout << “Your full name is: “ << full_name << endl;
getline(cin, address, ‘$’); //reads multiple lines
cout << “Your address is: “ << address << endl;
return 0;
}

first argument is the stream object from which the input will come.

second argument is the string object where the text will be placed.

The third argument specifies the character to be used to terminate the input. If no third argument is suppliedto getline(), the delimiter is assumed to be ‘\n’, which represents the Enter key.

0

Instead of cin.get() method use the following approach:

string s1,s2;
int max1,max2;
for (int i=0; i<max1; i++) 
{
 char ch = getchar();
 while (ch != '\n' && ch != EOF) {
 s1+=ch;
ch=getchar();
}
for (int i=0; i<max2; i++) 
{
 char ch = getchar();
 while (ch != '\n' && ch != EOF) {
 s2+=ch;
 ch=getchar();
}