Your input (underlined) is:
david 34 24
ls 45 35
haha 56 23 |
Note the extra space at the end of the first line. This causes the second line name to be \nls.
To fix this, change lines 19-22 to:
1 2
|
indata>>n1 >> n2;
indata.ignore(1000000, '\n'); // ignore a million characters or until newline is reached
|
Technically, the first arg to ignore() should be
numeric_limits<streamsize>::max()
. This guarantees that it will read and discard every character until it finds a newline, no matter how obscenely huge the file is.
Other comments:
Why have variables nm, n1 and n2 at all? Why not read the values directly into their final locations?
Line 29: don't use l (lower case el) as a variable name. It's too easy to mistake it for 1 (digit one). For example, a casual reader might roll their eyes at line 34 and mistakenly change it
char nama[3][2];
Speaking of line 34, it only works properly if the first name in the file is the longest one. Otherwise you'll overflow the strings.
Also speaking of line 34, you don't need it as repeater has pointed out.
I think it's clearer to put the "loopy" code in a for construct and have the body of a loop contain just the code that operates on each loop item, so I'd change line 17 to
for (n=0; getline(indata, nm, '\t'); ++n)
and remove line 26.
Line 36 should be
for(int i=0; i<n; i++)
Putting it all together:
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
|
#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;
int
main()
{
ifstream indata;
indata.open("name.txt");
int num[30];
int num2[30];
int n = 0;
string name[30];
for (n = 0; getline(indata, name[n], '\t'); ++n) {
indata >> num[n] >> num2[n];
indata.ignore(1000000, '\n');
}
for (int i = 0; i < n; i++) {
cout << name[i] << " " << num[i] << " " << num2[i] << endl;
}
return 0;
}
|