5

I'm reading data from a stream into a char array of a given length, and I'd like to make the maximum width of read to be large enough to fit in that char array.

The reason I use a char array is that part of my specification is that the length of any individual token cannot exceed a certain value, so I'm saving myself some constructor calls.

I thought width() did what I wanted, but I was apparently wrong...

EDIT: I'm using the stream extraction operators to perform the extraction, since these are flat text files with values separated by whitespace.

3
  • I don't understand. istream::read() lets you specify the amount of characters you want to read into a buffer. Why won't this work for you? Commented Mar 18, 2010 at 16:20
  • What I mean is that I want the extraction operators to limit themselves to a certain number of characters in length. The more I think about this, though, then more I realize this i probably not standard behavior... Commented Mar 18, 2010 at 16:26
  • Are your values all textual, or are some of them numbers? Commented Mar 18, 2010 at 18:10

2 Answers 2

5

If you're processing text, you're looking for the get function: http://cppreference.com/wiki/io/get

const int size = 200;
char myArray[size] = {};

cin.get(myArray, size);

Note: only size - 1 characters are read, which leaves a NULL terminator in myArray.

If it's raw data, you'd probably prefer read: http://cppreference.com/wiki/io/read

const int size = 200;
char myArray[size] = {};

cin.read(myArray, size);

size bytes are read.

Sign up to request clarification or add additional context in comments.

Comments

4
char x[4];
cin.width(4);
cin >> x;
cout << x;

Input: "abcdef"
Output: "abc" (x[3] is null terminating char)

Width works fine in this case.

Note: Empirical testing indicates that the cin.width call only lasts for one stream operation. It may be more convenient to use cin >> setw(4) >> x; instead, though this requires iomanip.

2 Comments

Note that if the input contains white-space this will fail. Try it for Input: "a b c d e f". Output: "a".
@Bill: I consider that a good thing. The OP said that the values are separated by whitespace.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.