2

I am storing words on run time in array but when i give space between words the program don't ask for second input it give me an output directly without taking second input here is my coding .

#include<iostream>
#include<conio.h>

using namespace std;
int main(){
char a[50];
char b[50];
cout<<"please tell us what is your language\t";
cin>>a;
cout<<"please tell us what is your language\t";
cin>>b;
cout<<a<<b;
getch();
}

here is my output

syed shah
  • 678
  • 1
  • 6
  • 22
  • 2
    Maybe you should use `std::getline` instead of the `>>` extraction operator, if you want to read lines and not white-space separated words. – dyp Sep 16 '13 at 04:54
  • Possibly relevant: http://stackoverflow.com/questions/5838711/c-cin-input-with-spaces – user2155932 Sep 16 '13 at 04:55
  • 3
    You shouldn't use `cin>>a;` if `a` is an array, because it's unsafe (if you don't provide a width via `cin >> setw(49)`). If anyone uses a word longer than 50 characters, you'll get buffer overflows, access violations and all kinds of undefined behaviour. Better use a `std::string`. – dyp Sep 16 '13 at 04:56
  • but i have declare the using keyword above why do i need std and scope resolution operator – syed shah Sep 16 '13 at 04:56
  • 1
    You don't, that's just the way I type it to make clear it's part of the Standard library ;) – dyp Sep 16 '13 at 04:57
  • ok sir let me try if you give me a little more idea i will be thank full to you – syed shah Sep 16 '13 at 04:58
  • std::string c; i have try like that is it right ? – syed shah Sep 16 '13 at 05:04

1 Answers1

4
#include<iostream>
//#include<conio.h>    // better don't use this, it's not portable
#include <string>

//using namespace std; // moving this inside the function
int main(){
    using namespace std;  // a bit more appropriate here

    string a;
    string b;

    cout<<"please tell us what is your language\t";
    getline(cin, a);  // `a` will automatically grow to fit the input
    cout<<"please tell us what is your language\t";
    getline(cin, b);
    cout<<a<<b;

    //getch();            // not portable, from conio.h
    // alternative to getch:
    cin.ignore();
}

A reference for std::getline (with an example at the bottom) and std::string.

dyp
  • 38,334
  • 13
  • 112
  • 177