Help please : problem with char[32]

Hi everyone! I'm new to C++ and I'm struggling on this very small program.

1
2
3
4
5
6
7
8
9
10
11
#include <iostream>

int main()
{
	char str1[32];
	std::cout<<"What your name? ";
	std::cin>>str1;
	std::cout<<"So, your name is "<<str1;
	return 0;
}


The problem is that when I enter 'Ashish Kushwaha' to str1, it shows only Ashish and neglect Kushwaha . It's strange because total elements in str1 is 33 and it should be able to a 15 bytes variable, but its not doing it.
istream's operator<< skips initial spaces, reads non-space characters, and stops reading when it encounters a space. So it's particularly good at reading space-separated words, although it has no protection against overflowing a C-style string.

The getline member of istream will read up to a given character (such as '\n' if you want to read a line). It doesn't skip initial spaces and reads up until the given character (which it extracts from the input but does not put into your string). It also takes the size of the char array so that it doesn't overflow it.

1
2
3
4
5
6
7
8
9
10
#include <iostream>
using namespace std;

int main()
{
	char str1[32];
	cout<<"What your name? ";
	cin.getline(str1, sizeof str1, '\n');
	cout << "So, your name is " << str1 << '\n';
}


However, in C++ it's best to avoid C-style strings when possible and use a C++ std::string instead (which can accept as many chars as necessary, up to billions of chars, at least). So it's better to do something like this:

1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
#include <string>
using namespace std;

int main()
{
	string name;
	cout << "What your name? ";
	getline(cin, name);
	cout << "So, your name is " << name << '\n';
}

Last edited on
tpb wrote:
it has no protection against overflowing

it does: std::cin >> std::setw(32) >> str1;. But std::string is indeed a far better solution.
@Cubbi, very good point. I didn't think of that. Should it maybe be setw(31)? I'm thinking it might be like the scanf limits which don't include space for the '\0'. I'm not sure about that, though.
Last edited on
@Cubbi, It's good they changed that from scanf.
The extraction stops if one of the following conditions are met:
* a whitespace character (as determined by the ctype<CharT> facet) is found. The whitespace character is not extracted.
* stream.width() - 1 characters are extracted
* end of file occurs in the input sequence (this also sets eofbit)

Thank you everyone for helping me! 🙂
Topic archived. No new replies allowed.