#define _CRT_SECURE_NO_WARNINGS #include "stdafx.h" #include "conio.h" #include <iostream> #include <fstream> #include <stdio.h> #include <string> using namespace std; int main() { FILE *f; char obr[15]; char fam[15]; char name[15]; char tel[10]; char p[20]; int n = 0; puts("File name:"); scanf("%s", &p); f = fopen(p, "rt"); puts("Enter surname:"); scanf("%s", &obr); while (!feof(f)) { fscanf(f, "%s %s %s", &fam, &name, &tel); if (fam == obr) { printf("%s %s %s", fam, name, tel); n++; } } if (n) { printf("Number of records: %i\n", n); } else { printf("No data. %i", n); } fclose(f); system("pause"); } 

Help me find an error in the code, during the execution of the program the counter is n = 0, although I have such an entry in my notebook "Ivanov Vasya 900-90-90". The essence of the program: if there is a surname in Notepad that matches the one entered by the user, then we display the data associated with this surname and count the number of records found, that is, n.

  • And what exactly is a mistake? The code is there, but there is no error ... Give a partial example of the contents of the file and what you type in the console. - Daniel Protopopov
  • If they wrote on the pros, not on C, and used the type std :: string, then the comparison would go well. - KoVadim
  • @KoVadim In my opinion, you need to write a FAQ :) This question - comparing pointers instead of content - is a constant misfortune. - Harry
  • Yes, and it should contain links to real paper books with pages and line numbers. - KoVadim
  • @KoVadim I already wrote in C ++, focusing on the book "C / C ++ in problems and examples" of N. Cultin 2002. - Martin Eden

1 answer 1

Instead of this cycle

 #include <string> ^^^^^^^ //... while (!feof(f)) { fscanf(f, "%s %s %s", &fam, &name, &tel); ^^^ ^^^ ^^^ if (fam == obr) ^^^^^^^^^^ { printf("%s %s %s", fam, name, tel); n++; } } 

write

 #include <cstring> ^^^^^^^ //... while ( fscanf(f, "%s %s %s", fam, name, tel) == 3 ) ^^^ ^^^ ^^^ { if ( strcmp( fam, obr) == 0) ^^^^^^^^^^ { printf("%s %s %s", fam, name, tel); n++; } } 
  • Thanks, it helped, but now I will ask you to explain what was wrong, I cannot remain indifferent to learning the language - Martin Eden
  • one
    @MartinEden I highlighted in my answer with a stroke what was wrong. For example, the header, string> is the standard C ++ header to declare the class std :: string, while the strcmp function used in the program is declared in the standard C header, which in C ++ is written as <cstring> - Vlad from Moscow
  • those. with the addresses of variables do not work? - Martin Eden
  • @MartinEden The% s format specifier is waiting for an argument of type char *, not of type char **. - Vlad from Moscow
  • one
    @MartinEden I have not dealt with this book, but, most likely, if this is true, then there is an error. - Vlad from Moscow