-2
#include "stdafx.h"
#include <iostream>
#include <string>
#include <sstream>
using namespace std;

int main()
{
string a;
string b = "hey";
cin >> a;
if (a == b) {
    cout << "hello \n";

}

int z = 40;
string x = "";
string y = "weather";
cin >> x;
if (x == y) {
    cout << "the temp is " << z << endl;
}
return 0;
    }

it works correctly but once I change string y to a sentence that have spaces in it it does not work for example : string y = "this is a sentence";

Ahmad Diaa
  • 11
  • 1
  • 2
  • 3
    `cin >> x;` will read into `x` until it finds whitespace. Use `getline` to get strings with included whitespace (up to the delimiter). – crashmstr May 01 '17 at 18:50
  • 2
    Possible duplicate of [std::cin in input with spaces?](http://stackoverflow.com/questions/5838711/stdcin-in-input-with-spaces) – Cherubim May 01 '17 at 18:50

1 Answers1

1

Use getline() function or you can also use gets() function.

If you are using STL string then,

getline(cin,str);   /*it will work */

If you are not using STL string then,

#include <cstdio>
char *gets( char *str );
Zaid Khan
  • 357
  • 4
  • 14
  • 1
    Never use `gets`, **especially** in C++. – Daniel Kamil Kozar May 01 '17 at 18:55
  • Please see [this question](http://stackoverflow.com/questions/1694036/why-is-the-gets-function-so-dangerous-that-it-should-not-be-used). – Daniel Kamil Kozar May 01 '17 at 18:57
  • Thanks for answer but sadly I can't do it now I am still learning I haven't learned that yet I just though to create very simple chat bot maybe 5 or 6 sentences with what I learnt but it seems I need to learn more – Ahmad Diaa May 01 '17 at 19:09