I would like to read from a file using cin and redirection and place them into a 2d array. Unfortunately, I keep getting a segfault because of the blank spaces after the input file, (I've checked and there are no blank spaces after the last character. Here's what I have.
input.txt
abcd
efgh
ijkl
mnop
Here's a snippet of my code:
char c;
int i =0; int j=0;
while(cin >> c){
ary[i][j] = c;
++i;
++j;
}
The goal is to have a matrix like this:
['a', 'b', 'c', 'd']
['e', 'f', 'g', 'h']
['i', 'j', 'k', 'l']
['m', 'n', 'o', 'p']
Is there a way to tell cin to ignore all blank spaces or newlines after the letter p? I tried cin.get(c) and that doesn't seem to do the trick. Here's how I'm running my script: ./executable < input.txt
Thanks in advance
Run the script in your head. See what output it provides. You will clearly see you can never reference ary[0][1], ary[0][2], etc.
Did you try using debugger? It's a really useful tool.
Anyway; you need to do something different - I suggest you using for
loop:
for(int i = 0; i < 4; ++i)
{
for(int j = 0; j < 4; ++j)
{
std::cin >> tab[i][j];
}
}
Usually if you're operating on tabs or input with fixed size(like yours), you want to use for loop - easier to manage
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.