reading in a string of a specified length

I am attempting to read in a string of 123 characters and strip out certain fields. The string 'can' contain allot of blanks and special characters; example: A00034A16 V006 * C 136-01 0001-9999 A2160-CB2E10 1 A2160-J6 &M 922 . It appears my string input is have troubles with the blanks and ends prior to reading the entire line:

while ( !inputFile.eof() )
{

inputFile >> myString;

newString = myString.substr(0,9);
messageOut << newString;
messageOut << dot;
newString = myString.substr(69,12);
messageOut << newString;
messageOut << dot;

While the syntax is correct I receive an error at run time: 'std::out_of_range' what(): basic_string::substr. Some how there has to be a way of loading all 123 characters from the input string into 'myString'. What am I missing. ( I even attempting reading in a char[123] and equating it to 'myString' to no avail). Thanks for your assistance!!

By the way, when I previewed this message allot of blanks were omitted from the example line. Between A00034A16 and V006 there are actually 20 spaces.
Use std::getline instead. Or, if it can contain newline characters, you will have to read in binary mode.
You can use something like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <fstream>

int main()
{
	std::ifstream ifs("input.txt", std::ios::binary);

	char buf[123];

	// try to read 123 chars, len contains the actual number read
	int len = ifs.readsome(buf, 123);

	// Did we read anything? (you may want to check that len == 123 here)
	if(len > 0)
	{
		// Ok, turn it into a std::string
		std::string line(buf, len);

		// now examine the string...
	}

	return 0;
}
Last edited on
Topic archived. No new replies allowed.