There was a problem reading the lines from the file. Here is the code:

#define SIZE 15 #define MAX 20 struct new { char surname[SIZE]; char name[4]; }user_str[MAX_RECORD]; using namespace std; int main() { FILE *input; input = fopen("input.txt", "r"); for (int i = 0; i < 2; i++) { fscanf(input, "%s %s\n",user_str[i].surname, user_str[i].name); } printf("%s %s\n", user_str[0].surname, user_str[0].name); 

I will explain the essence of the program: a text file is given, in which there are two lines and written in them: Last Name First Name, in the format: Family IO You must read this file and write data to the structure.

For example, a text file looks like this: Ivanov II Petrov KK

However, when trying to output user_str[0].surname, user_str[0].name prints Ivanov IIPetrov , but should simply Ivanov II .

What could be the problem?

    1 answer 1

    At least you have a name - 4 characters, and you read 4 characters into it. And where is the zero terminator written? Yes, precisely - outside the structure. Most likely, already in the following structure - and there it is hammered by entering the next surname. Here you get it ...

    Do not regret the memory. And then suddenly you will be OSBM Bender-Zadunaysky - see for yourself that your size will not be enough. It is better to use safe functions in the spirit of _s or otherwise monitor how many characters are being entered - buffer overflow is just an invitation to get in trouble to visit ...

    • Thanks for the answer, I will take note) - Vyacheslav