Версия для печати темы
Нажмите сюда для просмотра этой темы в оригинальном формате
Форум программистов > C/C++: Общие вопросы > ошибка в code:blocks


Автор: xcf 31.1.2006, 21:22
в code:blocks след
запускаю прогу

Код

#include <iostream.h>
#include <conio.h>
#include <math.h>
void main()
{
 clrscr();
 const int n=5;
 int a[n],c[n],i,x,h;
 double k;
 cout<<"\n vvdite masiv";
 for(i=0;i<n;i++)
        {
        cin>>a[i];
        }
        k=0;h=0;
 for(i=0;i<n;i++)
        {
                k=i%2;
                if (k==1) cout<<a[i]<<"\n";
                else {c[h]=a[i];h+=1;}
        }
 for(i=0;i<h;i++)
 cout<<"\n"<<c[i];
 getch();
}

а он мне выдает следущие
Compiling: C:\9.c
C:\9.c:1:22: iostream.h: No such file or directory
C:\9.c: In function `main':
C:\9.c:12: error: `cout' undeclared (first use in this function)
C:\9.c:12: error: (Each undeclared identifier is reported only once
C:\9.c:12: error: for each function it appears in.)
C:\9.c:13: error: `cin' undeclared (first use in this function)
C:\9.c:5: warning: return type of 'main' is not `int'
C:\9.c:25:2: warning: no newline at end of file
Process terminated with status 1 (0 minutes, 1 seconds)
5 errors, 2 warnings
проверял в корневой папке наличие библиотеки все наместе.
в чем дело?
надеюсь на скорою помощь


M
chipset
Используем теги [code=cpp].

Автор: BreakPointMAN 31.1.2006, 22:12
поиграйся с #include, возможно, code:blocks хочет, чтобы было все по-новому стандарту, т.е. "iostream", а не "iostream.h"...
кстати, кажется, он и на функцию main будет ругаться, требуя, чтобы она возвращала int-значение... smile

Автор: chipset 31.1.2006, 22:14
Код

#include <iostream>
using namespace std;

Автор: xcf 1.2.2006, 08:22
изменяю на
Код

#include <iostream>
#include <conio>
#include <math>
int main()

выдает следущеи

Compiling: C:\9.c
C:\9.c:1:20: iostream: No such file or directory
C:\9.c:2:17: conio: No such file or directory
C:\9.c:3:16: math: No such file or directory
C:\9.c: In function `main':
C:\9.c:12: error: `cout' undeclared (first use in this function)
C:\9.c:12: error: (Each undeclared identifier is reported only once
C:\9.c:12: error: for each function it appears in.)
C:\9.c:13: error: `cin' undeclared (first use in this function)
C:\9.c:25:2: warning: no newline at end of file
Process terminated with status 1 (0 minutes, 0 seconds)
7 errors, 1 warnings
есть по code:blocks how to на руском smile

Автор: Romikgy 1.2.2006, 12:57
А пути прописанны? к инклюдам?
да и
Цитата(chipset @ 31.1.2006, 21:14 Найти цитируемый пост)

using namespace std;


Автор: xcf 1.2.2006, 14:00
в настройках прописано расположение библиотек
копировал из bcw 3.1 все ттоже самое

Автор: Partizan 1.2.2006, 16:20
мдя....попробуй скниуть нужные *.h файлы туда же где лежит исходник и поменяй <... .h> на "... .h "

Автор: xcf 1.2.2006, 16:48
возникла новая проблема
Код

#include <iostream.h>
#include <conio.h>
#include <math.h>
using namespace std;
void main()


Compiling: C:\inf\ERT.CPP
In file included from C:/Program Files/CodeBlocks/bin/../lib/gcc/mingw32/3.4.4/../../../../include/c++/3.4.4/backward/iostream.h:31,
from C:\inf\ERT.CPP:1:
C:/Program Files/CodeBlocks/bin/../lib/gcc/mingw32/3.4.4/../../../../include/c++/3.4.4/backward/backward_warning.h:32:2: warning: #warning This file includes at least one deprecated or antiquated header. Please consider using one of the 32 headers found in section 17.4.1.2 of the C++ standard. Examples include substituting the <X> header for the <X.h> header for C++ includes, or <iostream> instead of the deprecated header <iostream.h>. To disable this warning use -Wno-deprecated.
C:\inf\ERT.CPP:6: error: `main' must return `int'
C:\inf\ERT.CPP:26:2: warning: no newline at end of file
Process terminated with status 1 (0 minutes, 4 seconds)
1 errors, 2 warnings
проблема в том что когда void заменяешь на int результат проги не правльный

Автор: Romikgy 1.2.2006, 16:54
Код

#include <iostream>
#include <conio.h>
using namespace std;

int main()
{
    //clrscr();
 const int n=5;
 int a[n],c[n],i,x,h;
 double k;
 cout<<"\n vvdite masiv";
 for(i=0;i<n;i++)
        {
        cin>>a[i];
        }
        k=0;h=0;
 for(i=0;i<n;i++)
        {
                k=i%2;
                if (k==1) cout<<a[i]<<"\n";
                else {c[h]=a[i];h+=1;}
        }
 for(i=0;i<h;i++)
 cout<<"\n"<<c[i];
 getch();

    return 0;
}


Вот так работает, только проект создай и нет в
Цитата(xcf @ 31.1.2006, 20:22 Найти цитируемый пост)

code:blocks

ф-ции
Цитата(xcf @ 31.1.2006, 20:22 Найти цитируемый пост)

clrscr();

Это только борландовская фича

Автор: xcf 2.2.2006, 00:18
Цитата
проблема в том что когда void заменяешь на int результат проги не правльный

кто знает в чем дело?

Автор: Partizan 2.2.2006, 02:44
?!?!?! это как?

Автор: S.A.P. 2.2.2006, 08:37
Поставь int main(), а в конце return 0.
Цитата(xcf @ 2.2.2006, 00:18 Найти цитируемый пост)

проблема в том что когда void заменяешь на int результат проги не правльный

а какой правильный? smile .

Автор: Romikgy 2.2.2006, 09:48
xcf дык покажи че выдает , и че должно быть , а мы подскажем че править smile

Автор: xcf 2.2.2006, 09:48
если посмотреть на этот цикл
Код

for(i=0;i<n;i++)    
        {    
                k=i%2;    
                if (k==1) cout<<a[i]<<"\n";    
                else {c[h]=a[i];h+=1;}
         }

то внем используется тип double
что при использовании int что не дает правильного результата
а вообще прога должна упорядочить масив по четным и нечетным числам

Автор: Romikgy 2.2.2006, 09:52
Так в чем трабла, замени на инт

Автор: xcf 2.2.2006, 09:54
а вообще прога должна упорядочить масив по четным и нечетным числам

Автор: volvo877 2.2.2006, 10:04
Ну, а ты упорядочиваешь по индексам smile

Держи:
Код

#include <iostream>
#include <conio.h>
using namespace std;

int main()
{
  const int n = 5;
  int a[n],c[n],i,h;
  
  cout<<"\n vvdite masiv";
  for(i=0;i<n;i++) {
      cin >> a[i];
  }
  h = 0;
  for(i=0;i<n;i++) {
      if (a[i]%2==1) cout<<a[i]<<"\n";
      else c[h++]=a[i];
  }
  for(i=0;i<h;i++)
    cout<<"\n"<<c[i];
  getch();
  return 0;
}

Автор: xcf 2.2.2006, 11:49
спасибо volvo877 за помощь но опять выдает ошибки
Compiling: C:\inf\code\Untitled1.c
C:\inf\code\Untitled1.c:1:22: iostream.h: No such file or directory
C:\inf\code\Untitled1.c:3: error: syntax error before "namespace"
C:\inf\code\Untitled1.c:3: warning: data definition has no type or storage class
C:\inf\code\Untitled1.c: In function `main':
C:\inf\code\Untitled1.c:8: error: `cout' undeclared (first use in this function)
C:\inf\code\Untitled1.c:8: error: (Each undeclared identifier is reported only once
C:\inf\code\Untitled1.c:8: error: for each function it appears in.)
C:\inf\code\Untitled1.c:10: error: `cin' undeclared (first use in this function)
C:\inf\code\Untitled1.c:21:2: warning: no newline at end of file
Process terminated with status 1 (0 minutes, 0 seconds)
6 errors, 2 warnings

PS Я наверно уже надоел со своими ошибками

Автор: Romikgy 2.2.2006, 11:56
Замени в рабочем коде между
Код

int main()
{
 // все это на
}

Код

const int n = 5;
  int a[n],c[n],i,h;
  
  cout<<"\n vvdite masiv";
  for(i=0;i<n;i++) {
      cin >> a[i];
  }
  h = 0;
  for(i=0;i<n;i++) {
      if (a[i]%2==1) cout<<a[i]<<"\n";
      else c[h++]=a[i];
  }
  for(i=0;i<h;i++)
    cout<<"\n"<<c[i];
  getch();
  return 0;

вот это , но только там где работало smile

Автор: volvo877 2.2.2006, 12:01
xcf, у тебя что-то с настройками... Дело в том, что я копировал текст из окна MinGW Studio. Там все отработало прекрасно. Должно работать и в code:blocks.

Цитата(xcf @ 2.2.2006, 10:49 Найти цитируемый пост)
C:\inf\code\Untitled1.c:1:22: iostream.h: No such file or directory
Это откуда? У меня в коде <iostream> стоит... Ты бы ПОЛНОСТЬЮ код отсюда копировал, и только потом тестил...
Добавлено @ 12:02
АААА !!! Ты файл как назвал? Это же CPP !!! smile

Автор: Romikgy 2.2.2006, 12:07
Цитата(volvo877 @ 2.2.2006, 11:01 Найти цитируемый пост)

АААА !!! Ты файл как назвал? Это же CPP !!!

Имхо побоку , в среде указываешь какой код smile
Я тестил в
Цитата(volvo877 @ 2.2.2006, 11:01 Найти цитируемый пост)

code:blocks

и номано smile

Автор: xcf 2.2.2006, 17:51
файл н-ся *.с исправил на *.срр все нормально пошло
volvo877
я полностью код вставлял
Romikgy
можно в code:blocks настороить что он сразу сохранял как *.срр

вот новая проблема
Код

#include <conio.h>
#include <stdlib.h>
#include <time.h>
using namespace std;
int main()
{
    int comp;
    int igrok;
    int n;
    time_t t;
    srand((unsigned)time(&t));
    comp=rand()%10+1;
    cprintf("\n\rkomp'uter\"zadumal\" 4isloot 1 do\19.\n\r");
    cprintf("vbl dolgnbl ygadat' za 3 popbltki");
    n=0;
    do {
        cprinf("\n\r->");
        cscanf("%i",&igrok);
        n++;
    }
    while ((igrok!=comp)&&(n<3));
    if (igrok==comp)
    {
        textcolor(red+blink);
        cprinf("\n\r vbl vbligrali");
    }
    else
    {
        textcolo(green);
        cprinf("\n\r vbl proigrali");
        cprinf("\n\r komp zadymal 4islo %d",comp);
    }
    textcolor(lightgray);
    cprinf("\n\r dl9 zav nagm kl");
    getch();getch();
}

следущие ошибки
Compiling: C:\inf\code\1.c
C:\inf\code\1.c:5: error: syntax error before "namespace"
C:\inf\code\1.c:5: warning: data definition has no type or storage class
C:\inf\code\1.c: In function `main':
C:\inf\code\1.c:25: error: `red' undeclared (first use in this function)
C:\inf\code\1.c:25: error: (Each undeclared identifier is reported only once
C:\inf\code\1.c:25: error: for each function it appears in.)
C:\inf\code\1.c:25: error: `blink' undeclared (first use in this function)
C:\inf\code\1.c:30: error: `green' undeclared (first use in this function)
C:\inf\code\1.c:34: error: `lightgray' undeclared (first use in this function)
C:\inf\code\1.c:37:2: warning: no newline at end of file
Process terminated with status 1 (0 minutes, 1 seconds)
7 errors, 2 warnings

Автор: S.A.P. 2.2.2006, 18:28
xcf откуда ты вобще этот код откопал??? Судя по всему он предназначался для Борлы, а ты как я понял на VCT сидишь.

Автор: xcf 2.2.2006, 21:19
извеняюсь за глупые фопросы
S.A.P.
Цитата

VCT

что это такое?
этот код из задачника для си
к тому же разве нет разници(большой) между средами разработки я так думаю что синтаксис везде одинаковый должен быть тк си должен портироваться на все платформы без ощютимых изменений...
а у меня стоит bcw 3.1 и code:blocks скачал нравится то что синтаксис делает тк положено
а у меня с ним одни проблемы mvs не хочю устанавливат слишком мног ресурсов жрет и места занимает...

Автор: ЧихПых 16.3.2006, 18:14
Привет! У меня такая ошибка:

Project : Console application
Compiler : GNU GCC Compiler (called directly)
Directory : D:\Projects\matrix\
--------------------------------------------------------------------------------
Switching to target: default
Linking console executable: D:\Projects\matrix\matrix.exe
.objs\main.o:main.cpp:(.text+0x1bd): undefined reference to `Rus(char const*)'
.objs\main.o:main.cpp:(.text+0x474): undefined reference to `Rus(char const*)'
.objs\main.o:main.cpp:(.text+0x49c): undefined reference to `col_line(int**, int)'
collect2: ld returned 1 exit status
Process terminated with status 1 (0 minutes, 0 seconds)
0 errors, 0 warnings

Можете объяснить что произошло, до этого нормально всё компилировалось smile

Автор: xcf 3.6.2007, 00:35
првиет) 
чтоб не плодить темы с ошибками я решил написать в ту тему...
C:smile в след соистенге пишет следующие 
Код

void AUTO::SaveDB(int filetype=0) // метод класса, сохраняющий БД в файл
{
  int i; // счетчик
  FILE *fout; //потоковая файловая переменная
  switch (filetype) //выбор сохраняемого файла
  {
    case 0: fout = fopen("input.txt","w");cout<<"\nInput_file saved\n";break;//открытие файла input.txt
    case 1: fout = fopen("result1.txt","w");break; // открытие для записи файла result1.txt
    case 2: fout = fopen("result2.txt","w");break; // открытие для записи файла result2.txt
  }
  for(i=0;i<n;i++) //цикл вывода записей в файл
     fout<<setw(20)<<mash[i].f.fam<<setw(20)<<mash[i].f.name<<setw(20)<<mash[i].f.ot<<setw(20)<<mash[i].marka<<setw(5)<<mash[i].god<<setw(20)<<mash[i].strana<<endl;
  fclose(fout); // закрытие файла
}


на строке fout<<setw(20)<<mash[i].... выдает следующию ошибку 
eror: no math for 'operator<<' in ' fout << std::setw(20)'
та же самая сторока только для cout никаких ошибок...

Автор: JackYF 3.6.2007, 14:51
Цитата(xcf @  3.6.2007,  00:35 Найти цитируемый пост)
FILE *fout; //потоковая файловая переменная


FILE* - это не потоковая файловая переменная.
Потоковая файловая переменная - fstream.

Код

std::ofstream fout("input.txt");


Powered by Invision Power Board (http://www.invisionboard.com)
© Invision Power Services (http://www.invisionpower.com)