Not the character 0. The number 0. Let's go back one.
When you use a char pointer for a string, what you actually have is an array of char. For example, if you want the name "james" the array looks like this
in memory:
| j | a | m | e | s |
The char pointer indicates the first letter, the "j". When you pass the char pointer to your printf, the function starts with the "j" and then prints out the "a", and then the "m", and then the "e", and then the "s"..... but how does it know when to stop? Maybe the name is actually "james123"? Maybe the string is "james went to town". How does it know where to stop?
It knows because the number zero is on the end. Not the character 0. The actual number. The array in memory should look like this:
| j | a | m | e | s | 0 |
When you're using char pointers for this sort of thing, you must put a zero value in the char array yourself, after the last character that is part of your string.
The zero char is not the same as the number zero. In memory, the character '0' has the numerical value 48. The actual number 0 has the numerical value 0.
Also, if i run my program more than once, even though I'm using the same imput file, the results are different. |
When you create your arrays like this:
char num[30],pren[30];
are they empty? No, they are not. They are blocks of memory containing whatever values were in that memory. Could be anything, and will often be different every time. Because you're passing these to printf, it will print out some of them each time, and they will be different each time.
If you used proper C++ strings, you wouldn't have any of this trouble, but it's worth you understanding what a char* actually is and how a char array works. Not understanding will cripple your programming ability in the future.
Edit: All that said, I must confess that I can't run your code to test it because headers etc are missing. The following simple code has no trouble at all reading and outputting your file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
#include<cstdio>
#include<fstream>
int main() {
int id;
std::ifstream f("membrui.txt");
char num[30],pren[30];
while(!f.eof())
{
f>>num>>pren>>id;
printf("%d\t",id);
printf("%s\t",num);
printf("%s\t",pren);
}
return 0;
}
|
and this does the same (and a bit more in the way of storage) in a much more C++ way
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 31 32 33 34 35 36 37 38 39
|
#include <fstream>
#include <string>
#include <iostream>
#include <vector>
struct member
{
int id;
std::string num;
std::string pren;
};
int main() {
int id;
std::ifstream f("membrui.txt");
std::vector<member> memberList;
// gather all data
while(!f.eof())
{
member tempMember;
f>>tempMember.num>>tempMember.pren>>tempMember.id;
if (!f.eof())
{
memberList.push_back(tempMember);
}
}
// output all data
for (int i=0; i<memberList.size(); ++i)
{
std::cout << memberList[i].id << " "
<< memberList[i].num << " "
<< memberList[i].pren << std::endl;
}
return 0;
}
|