spaces in char array input - C++

closed account (STR9GNh0)
char nam[MAX];

cout << "Enter item for sale: ";
cin >> nam;
cin.clear();
cin.ignore (10, '\n');
cout << "\n";


i tried using cin.getline but am unable to generate any output from name pertaining to 1 with spaces..

eg. if i enter the name James - it will output "James", without any issues...

but when i entered "James Man" it only take in "James" and leaving "Man" out.

Is there a way for me to join it ?
Yes, use getline().

I recommend you avoid using a char array and instead use a standard string:

1
2
#include <iostream>
#include <string> 
1
2
3
string name;
cout << "Enter name of item for sale: " << flush;
getline( cin, name );

Hope this helps.

[edit] Oh yeah, the std::istream's getline() method will work on char arrays.l
Last edited on
closed account (STR9GNh0)
thanks for the reply,

could you elaborate more on this instead?

std::istream's getline()

i have to use char no matter what (is part of the criteria). sorry.

or if possible, is there a way (besides using pointer) to convert char to string and later back on without affecting the data that is going to input ?
Last edited on
http://www.cplusplus.com/reference/iostream/istream/getline/
Here is some information of std::istream's getline(). You can use it to read data into a char array.
closed account (STR9GNh0)
sorry, i've tried above and it doesn't work

before i actually come in here
Last edited on
closed account (D80DSL3A)
This code is working for me:
1
2
3
4
5
6
7
8
9
10
#include<iostream>
using namespace std;

int main()
{
	char name[80];
	cout << "Name: ";
	cin.getline( name, 80, '\n' );
	cout << "Echo: " << name << endl;
}
closed account (STR9GNh0)
~~~~~~~~~~~~~~~
Last edited on
closed account (STR9GNh0)
any assistance?

thanks.
closed account (STR9GNh0)
thanks, i've managed to solve it by myself already
Last edited on
Topic archived. No new replies allowed.