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 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 |
#include <stdio.h> /*Включение в текст программы*/ #include <conio.h> /*определений и описаний функций*/ #include <string.h> /*для работы с консолью, строками*/ #include <math.h> /*и расчета математических формул*/ #include <ctype.h> int c[28][28],l[28],a[28]; /*Глобальное задание массивов*/ float p1[28]; void huffman (int,float *); /*Задание прототипов функций*/ int up (int,float); void down (int,int); main () { FILE *f,*f1; /*Определение структуры типа файл*/ char name[10]="",ch,ch1,name1[10]="",str[3],ch2[28],t1; /*Определение типов переменных и массивов*/ int j,i,prob=0,zn_pr=0,n=0,m[26],nn,rev,b,e,zn,r,nol=0,ed=0; float p_prob,p_zn_pr,p[26],h1,h2,h3=0,h,t,p2[28],s,z,lsr,p_nol,p_ed,h_nol,h_ed,h_new; clrscr (); printf ("Укажите путь к текстовому файлу nдля которого будет построен код Хаффмана: "); gets(name); if ((f=fopen (name,"rt")) == NULL) /*Проверка наличия указанного файла*/ {printf ("Не удается открыть заданный файл!"); getch(); return 0;} for (i=0;i<26;i++) m[i]=0; sn: while (!feof(f)) { /*В цикле реализован подсчет символов встречающихся в тексте*/ ch=getc(f); if (ch!=10) n++; if (ch==32) {prob++; continue;} if ((ch==44) || (ch==34) || (ch==39) || (ch==45) || (ch==46) || (ch==33) || (ch==63) || (ch==58) || (ch==59)) {zn_pr++; continue;} for (i=0;i<26;i++) if ((ch==(i+65)) || (ch==(tolower(i+65)))) {m[i]++; goto sn;} if ((ch!=10) && (ch!=255)) { clrscr (); printf ("Недопустимый символ в тексте!: %c",ch); getch (); fclose (f); return 0; } } if ((n-1)==0) {clrscr ();printf ("Файл пуст!");getch();fclose(f);return 0;} p_prob=(float)prob/(n-1); /*Расчет вероятностей появления символов*/ if (p_prob!=0) h1=p_prob*(log10(p_prob)/log10(2)); /*и энтропии исходного текста*/ p_zn_pr=(float)zn_pr/(n-1); if (p_zn_pr!=0) h2=p_zn_pr*(log10(p_zn_pr)/log10(2)); for (i=0;i<26;i++) { p[i]=(float)m[i]/(n-1); if (p[i]!=0) h3+=p[i]*(log10(p[i])/log10(2)); } h=-1*(h1+h2+h3); for (i=0;i<28;i++) { /*Формирование массива символов*/ if (i==26) {ch2[i]=32;p1[i]=p_prob;} /*и массива вероятностей символов*/ if (i==27) {ch2[i]=45;p1[i]=p_zn_pr;} if ((i!=26) && (i!=27)) {p1[i]=p[i]; ch2[i]=i+65;} } for (i=0;i<27;i++) /*Упорядочивание сформированных массивов*/ for (j=i+1;j<28;j++) /*по убыванию*/ if (p1[i]<p1[j]) { t=p1[i]; t1=ch2[i]; p1[i]=p1[j]; ch2[i]=ch2[j]; p1[j]=t; ch2[j]=t1; } for (i=0;i<28;i++) p2[i]=p1[i]; for (i=0;i<28;i++) /*Вычисление элементов*/ if (p1[i]==0) {nn=i-1;b=nn;break;} /*с ненулевой вероятностью*/ while (nn>0) { /*В цикле реализовано построение кода Хаффмана*/ huffman (nn,p1); nn--;} rev=nn+2; while (rev<=b) { e=a[rev]; down (rev,e); rev++; } printf ("n*************************Кодовая таблица****************************n"); for (i=0;i<=b;i++) { if (ch2[i]==32) printf ("nПробелt"); if (ch2[i]==45) {printf ("nЗн.преп.");r=i;} if ((ch2[i]!=32) && (ch2[i]!=45)) printf ("n%ct",ch2[i]); printf ("tp[%d]=%6.4ftl[%d]=%dtt",i,p2[i],i,l[i]); for (j=0;j<l[i];j++) printf ("%d",c[i][j]); getch (); } s=0; for (i=0;i<=b;i++) { z=-l[i]; s+=pow(2,z); } printf ("n*********************************************************"); printf ("nВыполнение неравенства Крафта-МакМиллана:"); if (s<=1) printf ("nНеравенство верно %6.4f<=1",s); else printf ("nНеравенство неверно %6.4f<=1",s); getch(); lsr=0; for (i=0;i<=b;i++) lsr+=p2[i]*l[i]; rep: printf ("nЗакодировать исходный текст полученным кодом? <yes/no>"); scanf ("%s",str); if (strcmp(str,"yes")==0) { printf ("nВведите имя файла для кодирования текста: "); scanf ("%s",name1); f1=fopen(name1,"wt"); rewind (f); while (!feof(f)) { /*В цикле реализовано кодирование исходного текста*/ ch=getc(f); /*полученным кодом Хаффмана*/ if ((ch==44) || (ch==34) || (ch==39) || (ch==45) || (ch==46) || (ch==33) || (ch==63) || (ch==58) || (ch==59)) for (j=0;j<l[r];j++) fprintf(f1,"%d",c[r][j]); else for (i=0;i<=b;i++) if (ch==(ch2[i]) || (ch==(tolower(ch2[i])))) for (j=0;j<l[i];j++) fprintf(f1,"%d",c[i][j]); } fclose(f); fclose (f1); printf ("nТекст успешно закодирован!"); getch (); n=0; f1=fopen(name1,"rt"); while (!feof(f1)) { /*В цикле реализован расчет энтропии закодированного файла*/ n++; ch=getc(f1); if (ch==48) nol++; if (ch==49) ed++; } p_nol=(float)nol/(n-1); /*Расчет вероятностей появления символов*/ if (p_nol!=0) h_nol=p_nol*(log10(p_nol)/log10(2)); p_ed=(float)ed/(n-1); if (p_ed!=0) h_ed=p_ed*(log10(p_ed)/log10(2)); h_new=-1*(h_nol+h_ed); fclose (f1); clrscr(); printf ("n*********************************************************"); printf ("nЭнтропия исходного файла: h=%6.4f",h); printf ("nСредняя длина кодового слова: lsr=%6.4f",lsr); printf ("nЭнтропия закодированного файла: h_new=%6.4f",h_new); getch(); } else if (strcmp(str,"no")==0) return 0; else goto rep; } /*Функции построения кода Хаффмана*/ void huffman (int n1,float p2[]) {int i; float q; if (n1==1) {c[0][0]=0;l[0]=1; c[1][0]=1;l[1]=1;} else { q=p2[n1-1]+p2[n1]; a[n1]=up(n1,q); } } int up (int n2,float q2) { int i,j; j=0; for (i=n2-1;i>0;i--) if (p1[i-1]<q2) p1[i]=p1[i-1]; else {j=i;break;} p1[j]=q2; return j; } void down (int x, int y) { /*Формирование кодовых слов*/ int s[28],l1,i,j; l1=l[y]; for (i=0;i<l1;i++) s[i]=c[y][i]; for (i=y;i<(x-1);i++) for (j=0;j<28;j++) { c[i][j]=c[i+1][j]; l[i]=l[i+1]; } for (i=0;i<l1;i++) { c[x-1][i]=s[i]; c[x][i]=s[i]; } c[x-1][i]=0; c[x][i]=1; l[x-1]=l1+1; l[x]=l1+1; } |
The ld returned 1 exit status
error is the consequence of previous errors. In your example, there is an earlier error—undefined reference to 'clrscr'
—and this is the real one. The exit status error just signals that the linking step in the build process encountered some errors. Normally, exit status 0
means success, and exit status
> 0 means errors.
When you build your program, multiple tools may be run as separate steps to create the final executable. In your case, one of those tools is ld, which first reports the error it found (clrscr
reference missing), and then it returns the exit status. Since the exit status is > 0, it means an error and is reported.
In many cases, tools return the number of errors they encountered as the exit status. So if the ld tool finds two errors, its exit status would be 2.
- Forum
- General Programming Boards
- C Programming
- clrscr code not working
-
05-14-2017
#1
Registered User
clrscr code not working
Hello
when I try to compile this code. my compiler show error message. I have mention code and error message. I think it s compiler error. I am using minGWCode:
#include<stdio.h> #include<conio.h> void main() { int a=10, b=20; int sum=0; clrscr(); // use clrscr() after variable declaration sum=a+b; printf("Sum: %d",s); getch(); }
hello.c: In function ‘main’:
hello.c:7:5: warning: implicit declaration of function ‘clrscr’ [-Wimplicit-function-declaration]
clrscr(); // use clrscr() after variable declaration
^
hello.c:9:22: error: ‘s’ undeclared (first use in this function)
printf(«Sum: %d»,s);
^
hello.c:9:22: note: each undeclared identifier is reported only once for each function it appears inHow to remove error
-
05-15-2017
#2
and the hat of int overfl
Well.
1. clrscr() comes from the DOS world, but you’re using a Win32 compiler.
2. main returns int, not void — another common DOS-world mis-conception.
3. In your printf statement, you use ‘s’ where you should be using sum.
-
05-15-2017
#3
Registered User
That’s a vendor-specific (and outdated) header file. It doesn’t exist in modern standard C, nor does any modern C compiler (that I know of) support it.
In general, that’s a platform-specific operation. There are some libraries (see CURSES) that are written for Windows and Linux that abstract terminal operations such as that. Even such a thing as «clearing the screen» is a complex operation that will require you to link to a 3rd party library that abstracts the complexity of that operation into a simple «clrscr» call.
Maybe you can simply remove the clrscr() call, and the include. There’s really no reason for it in this simple program.
Last edited by MacNilly; 05-15-2017 at 04:23 AM.
-
05-15-2017
#4
Registered User
I don’t have much knowledge. I am just doing simple program actually I wanted to see that how does Clrscr statement work in program. I tried different type of program. but still have looking same error.
-
05-15-2017
#5
Registered User
Originally Posted by MacNilly
That’s a vendor-specific (and outdated) header file. It doesn’t exist in modern standard C, nor does any modern C compiler (that I know of) support it.
In general, that’s a platform-specific operation. There are some libraries (see CURSES) that are written for Windows and Linux that abstract terminal operations such as that. Even such a thing as «clearing the screen» is a complex operation that will require you to link to a 3rd party library that abstracts the complexity of that operation into a simple «clrscr» call.
Maybe you can simply remove the clrscr() call, and the include. There’s really no reason for it in this simple program.
For the record, «conio.h» is NOT a «Vendor Specific» header file. It was first created by the Lattice C Compiler, back in 1982!
Before the C Programming Language was standardized in the 1989/1990 ANSI/ISO Standard, (And later by C99 & C11) compilers were free to implement their «Standard» Libraries, as they saw fit, primarily based on the K&R book, but with other functions (And «features») of their own.
Microsoft bought Lattice C to create their first compiler, including conio.h, and other compilers from that era also implemented conio.h in their compilers, Turbo-C among others.
As for «modern» C compilers, I can’t say which ones still have conio.h, and/or other Non-Standard Windows specific functions, as I only use and recommend Gcc and Clang. Programmers on all platforms should only use functions specified by the C Standards, except for some O/S specific reason.
In any case, functions provided by conio.h should never be used!
-
05-15-2017
#6
Registered User
conio.h is perfectly useable on Windows. It’s just not a portable way to do things. Also, it doesn’t seem to contain the clrscr command these days. Here’s three possible replacements:
See if the following works for you. I’ve heard that ANSI Control Codes actually work on some versions of Windows.
Code:
void cls(void) { printf("33[1J33[H"); }
If that doesn’t work then you could always use a system call. Since this calls a separate program it’s not a good way to do it if you’re clearing the screen a lot.
Code:
system("cls"); // On linux, use "clear" instead of "cls"
Or you could use the proper Windows functions. (I wish I could test this, but it’s just not physically (or mentally) possible. I’m particularly unsure about the GetStdHandle call.)
Code:
#include <windows.h> void cls(void) { HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE); COORD coordScreen = {0, 0}; DWORD cCharsWritten; CONSOLE_SCREEN_BUFFER_INFO csbi; DWORD dwConSize; GetConsoleScreenBufferInfo(hConsole, &csbi); dwConSize = csbi.dwSize.X * csbi.dwSize.Y; FillConsoleOutputCharacter(hConsole, (TCHAR)' ', dwConSize, coordScreen, &cCharsWritten); GetConsoleScreenBufferInfo(hConsole, &csbi); FillConsoleOutputAttribute(hConsole, csbi.wAttributes, dwConSize, coordScreen, &cCharsWritten); SetConsoleCursorPosition(hConsole, coordScreen); }
EDIT: Having said all that, you should probably also see if _clrscr() works (just in case!).
Last edited by algorism; 05-15-2017 at 09:57 AM.
-
05-15-2017
#7
Registered User
Thank you so much for your efforts. I tried your all tips but problem still remaining. should I change compiler. Should I use turbo c++
-
05-15-2017
#8
Registered User
NO!
Your best bet is to forget about trying to clear the screen, and if you do need to clear the screen just issue a bunch of line feeds until the screen is empty.
Also what type of project did you create? All of the functions defined in the conio.h file will only work with console programs, if you try to create some kind of Windows program they will not be available.
Jim
Last edited by jimblumberg; 05-15-2017 at 10:59 AM.
-
05-17-2017
#9
Registered User
vead (who is not the OP) is lying/joking.
-
05-17-2017
#10
and the hat of int overfl
Originally Posted by algorism
vead (who is not the OP) is lying/joking.
But they do have the same IP address.
-
05-19-2017
#11
Registered User
«But they do have the same IP address.»
Woah!
Anyways… Maybe I meant «non-standard» instead of «vendor-specific». Although, I bet different vendors DID provide different prototypes within «conio.h». I mean, since its not standard, every «conio.h» you’ll see is probably different. ANd Yes, you should use Tubro C++!!
-
05-24-2017
#12
Code Goddess
> Maybe I meant «non-standard» instead of «vendor-specific».
Meh, the end result is the same: you can’t depend on it being available or the same across compilers.
> I bet different vendors DID provide different prototypes within «conio.h».
Yes, they did indeed. For example, Microsoft’s compiler has conio.h, but clrscr isn’t provided. The behavior of the functions tends to be consistent, but lack of a guarantee is troublesome. As such, I typically recommend not using conio without an extremely strong reason. And most of the reasons don’t make the cut.
> ANd Yes, you should use Tubro C++!!
Why? And which version? Inquiring minds want to know, because unless you’re maintaining legacy code written in Turbo C++, this is almost guaranteed to be bad advice.
My best code is written with the delete key.
-
05-24-2017
#13
Registered User
Originally Posted by Prelude
> ANd Yes, you should use Tubro C++!!
Why? And which version? Inquiring minds want to know, because unless you’re maintaining legacy code written in Turbo C++, this is almost guaranteed to be bad advice.
It’s a joke son! I say a joke! ;^)
@Macnilly was only joking! Turbo C & C++ are both a joke! ;^)
gcc & clang are the only compilers I recommend and use.
Popular pages
- Exactly how to get started with C++ (or C) today
- C Tutorial
- C++ Tutorial
- 5 ways you can learn to program faster
- The 5 Most Common Problems New Programmers Face
- How to set up a compiler
- 8 Common programming Mistakes
- What is C++11?
- Creating a game, from start to finish
Recent additions
- How to create a shared library on Linux with GCC — December 30, 2011
- Enum classes and nullptr in C++11 — November 27, 2011
- Learn about The Hash Table — November 20, 2011
- Rvalue References and Move Semantics in C++11 — November 13, 2011
- C and C++ for Java Programmers — November 5, 2011
- A Gentle Introduction to C++ IO Streams — October 10, 2011
Similar Threads
-
Replies: 11
Last Post: 04-10-2011, 10:53 PM
-
clrscr()
By koyboy in forum C Programming
Replies: 3
Last Post: 05-24-2008, 11:01 AM
-
Replies: 7
Last Post: 04-22-2008, 11:20 AM
-
Replies: 2
Last Post: 08-02-2006, 12:51 PM
-
Replies: 3
Last Post: 03-05-2002, 12:42 PM
Tags for this Thread
/*Some non-Microsoft versions of C++ provide a clrscr function for clearing the screen in a DOS application.
However, there is no Win32 Application Programming Interface (API) or C-Runtime function that will perform this function.
There are two ways to accomplish this task for a Win32 console application. The first method is to use the system function as follows:*/
#include <stdlib.h>
void main()
{
system(«cls»);
}
/*
The second method is to write a function that will programmatically clear the screen.
That method is described in the More Information section which follows.
MORE INFORMATION
The following function clears the screen: */
/* Standard error macro for reporting API errors */
#define PERR(bSuccess, api){if(!(bSuccess)) printf(«%s:Error %d from %s
on line %dn», __FILE__, GetLastError(), api, __LINE__);}
void cls( HANDLE hConsole )
{
COORD coordScreen = { 0, 0 }; /* here’s where we’ll home the
cursor */
BOOL bSuccess;
DWORD cCharsWritten;
CONSOLE_SCREEN_BUFFER_INFO csbi; /* to get buffer info */
DWORD dwConSize; /* number of character cells in
the current buffer */
/* get the number of character cells in the current buffer */
bSuccess = GetConsoleScreenBufferInfo( hConsole, &csbi );
PERR( bSuccess, «GetConsoleScreenBufferInfo» );
dwConSize = csbi.dwSize.X * csbi.dwSize.Y;
/* fill the entire screen with blanks */
bSuccess = FillConsoleOutputCharacter( hConsole, (TCHAR) ‘ ‘,
dwConSize, coordScreen, &cCharsWritten );
PERR( bSuccess, «FillConsoleOutputCharacter» );
/* get the current text attribute */
bSuccess = GetConsoleScreenBufferInfo( hConsole, &csbi );
PERR( bSuccess, «ConsoleScreenBufferInfo» );
/* now set the buffer’s attributes accordingly */
bSuccess = FillConsoleOutputAttribute( hConsole, csbi.wAttributes,
dwConSize, coordScreen, &cCharsWritten );
PERR( bSuccess, «FillConsoleOutputAttribute» );
/* put the cursor at (0, 0) */
bSuccess = SetConsoleCursorPosition( hConsole, coordScreen );
PERR( bSuccess, «SetConsoleCursorPosition» );
return;
}
why do i get this error?
What error message do you get?
Odd. I’m not sure why it doesn’t recognize clrscr() when it recognizes getch().
-Albatross
P.S. — Even though the C language (I believe) will let it slide, it’s still a good idea to explicitly specify that main() returns an int
. C++, however, will not.
Last edited on
error C4430: missing type specifier — int assumed. Note: C++ does not support default-int
error C3861: ‘clrscr’: identifier not found
error C4430: missing type specifier — int assumed. Note: C++ does not support default-int
|
|
well do you see why that error cames out??
error C3861: ‘clrscr’: identifier not found
it is not found because first error isn’t resolved.
resolve first error, then clrscr will work just fine.
Last edited on
can you past your code . so that we can see it .
ok ..got it ..
try to use .
|
|
Last edited on
At the end of the day, how important is it that you clear the screen (an operation that goes against console programming philosophies) anyway?
-Albatross
http://en.wikipedia.org/wiki/Conio.h «The library functions declared by conio.h vary somewhat from compiler to compiler»
clrscr()
is not listed there.
¿Why you don’t copy-paste your code?
@imbaegod
how about using namespace std
???
@codekiddy
He’s using pure C. C doesn’t have namespaces.
-Albatross
Albatros,
He’s using pure C. C doesn’t have namespaces
I’m not shore about that since he is receiving errors related to C++ not C:
error C4430: missing type specifier — int assumed. Note: C++ does not support default-int
but maybe am I missing something here :/
The code is C, compiled with a C++ compiler.
conio.h is a non-standard header, so there is no guarantee of what is declared in it.
Topic archived. No new replies allowed.