Hi Bob!
On Sunday, November 13, 2016 at 2:04:27 PM UTC-5, Bob Langelaan wrote:
> ...
> The assignment specifies that each line of input will basically look like this:
>
> nnnnn nnnnnn string string <newline>
> <newline>
> nnnnn nnnnnn string string <newline>
> <newline>
> ...
>
> - Note - nnnnn simply represents an integer value. The strings will not contain any white-space.
>
> But input needs to handle error cases:
>
> nnnnn <newline> <-- missing last 3 values
> ...
> This is the first assignment for this class and their first use of the string class and therefore I would be surprised if they are required to use istringstream as part of their solution. And another possibility is to use a function like getchar() to read in each character, one by one, and manufacture the int and string values character by character.
>
> My question is there a better/easier way? This "better/easier way" would, I assume, need to be aware when a '\n' is encountered in the input stream.
Well, if this is the first assignment, it's a bit hard to
know what tools the students are expected / allowed to use.
But part of the point of c++ is to use the standard tools,
rather than write all of the low-level stuff from scratch.
So one suggestion that doesn't use too much machinery, is
pretty straightforward, and doesn't involve unnecessary
low-level coding runs as follows:
Use getline. This is perfectly appropriate because the input
format is explicitly line oriented.
Split the line into white-space-separated tokens. Count
the tokens. In your case, n != 4 is an error.
Parse / validate the tokens. In your case, tokens 3 and
4 are arbitrary (non-white-space-containing) strings, so
they are automatically valid. Tokens 1 and 2 are (decimal?)
integers, so parse them as such, and flag an error if they
are not.
I find it convenient to write a little helper function that
takes a std::string (obtained from getline) and returns a
std::vector<std::string> that contains the white-space-separated
tokens.
If tokens 1 and 2 are supposed to parse into a value that
fits into an unsigned int or unsigned long, you could use,
e.g., std::stoul. If they are supposed to parse into an
arbitrary length integer, then it's probably simplest to
write your own validation function that checks that each
character in the token is a (decimal) digit.
(I have used schemes like this frequently when writing
smallish programs that need to parse line-oriented input.)
> Thanks in advance :)
Happy Hacking!
K. Frank