Keyboard To Char Vector?

Hi Folks:

Developing on Windows 10 Pro, Visual Studio 2017 Community. As you can see, this is a console application.

I'm no C++ beginner, but it appears that I have no idea how to move text from a keyboard into a vector.

I put a breakpoint on the readcount assignment, after the call to read().

Start the program.

Enter some text and hit <CTL-C>.

Stepping through the code shows the vector is empty and gcount() has returned a value of 0.

Obviously, I'd like the vector to contain the text I've typed.

There are many ways to do things in C++, and I'm sure I could find other methods to read text, but I'm trying to follow some vendor supplied sample code that uses this construct, so I'd like to use std::cin.read() to populate the vector.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <vector>
#include <string>

int main ()
{
    std::vector<char> buf(2048);
    size_t readcount = 0;
    char *test_chars = 0;

    while(std::cin.good())
    {
        std::cin.read(buf.data(), sizeof(buf));
        readcount = std::cin.gcount();
        test_chars = buf.data();
    }

    return 0;
}


Thanks
Larry
Last edited on
Enter some text and hit <CTL-C>.
Stepping through the code shows the vector is empty and gcount() has returned a value of 0.

that's the expected result of hitting <Ctrl-C>: canceling any input and returning zero bytes.
If you wanted std::cin.read to write something to that vector, hit <Enter>, and then <Ctrl-Z>, and then <Enter> again. That's how Windows console signals end of input.

Alternatively, redirect the input from a file, the end of file will then signal the end of input

Alternatively, type more characters than the size submitted to cin.read() and press Enter

std::cin.read(buf.data(), sizeof(buf));

That uses the wrong size: use buf.size() instead of sizeof(buf)

while(std::cin.good())
this is also wrong: this checks the success of a read before attempting it instead of after, but it's not a big deal in your case (you have to be somewhat unlucky to hit the condition where it loops one more time due to this mistake, and even then you're recording and presumably checking gcount). Still, use proper C++:
1
2
while(std::cin.read(buf.data(), buf.size())) { readcount =
 ...
- all iostream read operations can be used as boolean conditions to test their success *after* the attempted read.
Last edited on
Thanks Cubbi:

<CTL-Z> <CR> fixed everything.

I never build console applications so I'm not familiar with this stuff.

That saves me some grief.

Larry
Last edited on
Topic archived. No new replies allowed.