std::string problems.
Feb 3, 2011 at 2:15am UTC
I can't seem to get get working with strings. Why can't I use infile.get(row, columns);?
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 28 29 30
#include<iostream>
#include<fstream>
#include<vector>
#include<string>
int main(int argc, char ** argv)
{
std::ifstream infile("test.txt" );
int columns, ctrl;
std::string row;
std::vector <std::string> matrix;
infile >> columns;
infile.get();
for (int i = 0; i < columns; i++)
infile.get(row[i]);
matrix.push_back(row);
for (int index = 1; !infile.eof(); index++)
{
ctrl = !(index%2)*(columns-1);
for (int i = 0; i < columns; i++)
infile.get(row[ctrl-i]);
matrix.push_back(row);
}
infile.close();
for (int j = 0; j < columns; j++)
for (int i = 0; i < matrix.size(); i++)
std::cout << matrix[i][j];
std::cin.get();
return 0;
}
........ CCCCCCCCmmmmmmmmdddddddd
test.txt contains:
5
A uoChdsWvee earrtl acoutis ondmC .
One more unrelated question. At first I accidentally forgot to #include<string>, but my program still compliled. Why?
Feb 3, 2011 at 2:25am UTC
infile.get(row[i]);
You never reserve the space in your string.
row.resize( columns );
edit: note that it is resize, no reserve, or you could corrupt the container.
Aharti.. eeuu uu ooCCooeeccmmCCeeaadd
what it should be?
I guess that some header does include at string.
Last edited on Feb 3, 2011 at 2:31am UTC
Feb 3, 2011 at 3:18am UTC
1 2 3 4
ctrl = !(index%2)*(columns-1); //ctrl=0 or ctrl=column-1
//ctrl = (index%2) ? 0 : columns-1;
//...
infile.get( row[ctrl-i] ); //if ctrl=0 -> out_of_range
Last edited on Feb 3, 2011 at 3:21am UTC
Feb 3, 2011 at 5:19pm UTC
Thanks, for some reason I thought string memory was automatically allocated when you add to the string. I had a lot of other mistakes but they're fixed now.
I still need to know if there is a way to use infile.get() to extract a specific amount of characters and store them in a std::string.
Feb 3, 2011 at 5:51pm UTC
Thanks, for some reason I thought string memory was automatically allocated when you add to the string.
And it is. But you were trying to access an out of bounds subscript. If you just did this:
1 2 3
char ch;
infile.get(ch);
row += ch;
it would have been fine.
Topic archived. No new replies allowed.