enter and isspace

Apr 6, 2018 at 8:37am
I've begun reading a bit about c type string functions and I've come across this strange behavior in my code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <cctype>
#include <iostream>
using namespace std;

bool numFormCheck(char[], int);

int main() {
	const int SIZE = 8;
	//Customer number:
	char custNum[SIZE];
	cout << "Enter a customer code in the format ";
	cout << "\"LLLNNNN\" (L for Letter, N for Number)\n";
	cin.getline(custNum, SIZE);
	if (numFormCheck(custNum, SIZE)) { cout << "This code is in the correct format\n"; }
	else { cout << "This code is in the wrong format\n"; }
	return 0;
}

bool numFormCheck(char custNum[], int size) {
	for (int i = 0; i < 3; ++i) {
		if (!isalpha(custNum[i])) return false;
	}
	for (int i = 3; i < size-1; ++i) {
		if (!isdigit(custNum[i])) return false;
	}
	if (!isspace(custNum[size-1])) { return false; }
	return true;}

the isspace() function I've used in the line before the last line is not working as I expect. For example I give this input "mbn1484[enter]" but isspace believes I've not entered any whitespace characters! and returns false.
Apr 6, 2018 at 8:49am
The newline character is not part of the string.
custNum[size-1] refers to the null character that marks the end of the string.
'm', 'b', 'n', '1', '4', '8', '4', '\0'
                                    ^
                                    |
                                    custNum[size-1]
Apr 6, 2018 at 10:47am
Thank you very much. This has solved my problem. Is this part of the Cplusplus.com reference referring to the same thing? That the newline character that I entered was discarded (and then a null character was replaced with it)?
If the delimiter is found, it is extracted and discarded (i.e. it is not stored and the next input operation will begin after it).
Apr 8, 2018 at 4:54pm
The reference page that you quoted is for the std::getline function which is not exactly the same as the getline member function that you're using.

http://www.cplusplus.com/reference/istream/istream/getline/
The delimiting character is the newline character ('\n') for the first form, and delim for the second: when found in the input sequence, it is extracted from the input sequence, but discarded and not written to s.

[...]

A null character ('\0') is automatically appended to the written sequence if n is greater than zero, even if an empty string is extracted.
Last edited on Apr 8, 2018 at 4:54pm
Topic archived. No new replies allowed.