Кресты / Говнокод #24716 Ссылка на оригинал

0

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
  36. 36
  37. 37
  38. 38
  39. 39
  40. 40
  41. 41
  42. 42
  43. 43
  44. 44
  45. 45
  46. 46
  47. 47
  48. 48
#include<iostream>
#include<fstream>
#include<vector>
using namespace std;
string rec(const string str, char c){return str;} //syntax error : missing ';' before identifier 'rec', ')' before 'const',  ')', ';' before '{', 
                                                                                //'str' : undeclared identifier, 'rec': identifier not found

void cer(){}                                                            //'cer' : local function definitions are illegal

main(){                                                                  //'main': identifier not found

	string s, d="Math.cos",a;                  //missing '}' before identifier 's',  ';' before identifier 's', 's', 'd', 'a' : undeclared identifier
	
        ifstream fin;
	vector<string> mas; // 'std::vector' : 'string' is not a valid template type argument for parameter '_Ty', 'mas' : unknown size
                                              //'std::vector' : no appropriate default constructor available

fin.open(mDocWrite); //'void std::basic_ifstream<char,std::char_traits<char>>::open(const char *,std::ios_base::open_mode)' : 
                                        //cannot convert argument 1 from 'nsAutoPtr<nsHtml5Tokenizer>' to 'const wchar_t *'
                     //No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called

//if (fin.is_open()) cout<<"1";else	cout<<"0";
while(fin>>s)    //'s' : undeclared identifier, fatal error C1903: unable to recover from previous error(s); stopping compilation
	{bool f=0;
		for(int i=0; i<s.size(); ++i)
			if (s[i]==d[0])
				{
					f=1;
					for (int j=0; j<s.size()&&j<d.size(); ++j)
						if (d[j]!=s[i+j]) f=0;
					if (f)
						{
							a.clear();
							for (int j=0; j<i; ++j)
								a=a+s[j];
							a=a+"0.5*";
							for (int j=i; j<s.size(); ++j)
								a=a+s[j];
						}
				}
						if (f)	{mas.push_back("\n");mas.push_back(a);mas.push_back("\n");}
			else mas.push_back(s);
			s=rec(s,'0');
	}
	ofstream fout;
fout.open(mDocWrite);
for (int i=0; i<mas.size(); ++i) fout<<mas[i]<<"\t";
}

предполагалось, что код будет уменьшать cos угла в два раза, но при компиляции выдает ошибки, логику большинства которых не могу понять. Ошибки указал в коде. Подскажите, что не так.

Запостил: DrAli DrAli, (Updated )

Комментарии (28) RSS

  • 05. Не подключен заголовок <string>.
    08. После предыдущей ошибки конпелятор думает, что эта строка находится внутри определения другой функции и жалуется на невозможность создания вложенных функций.
    10. C++ не поддерживает int по-умолчанию, тип возвращаемого функцией значения надо указывать явно.
    12., 15. Не подключен заголовок <string>.
    18. ifstream::open() принимает строку — имя файла, а mDocWrite — это не строка.
    23. Из-за ошибки на строке 12 переменная s как бы не существует, что и приводит к ошибке.

    Полезные ссылки:
    1) https://ru.wikipedia.org/wiki/Отступ_(программирование);
    2) https://ru.wikipedia.org/wiki/Стандарт_оформления_кода;
    3) http://8361.ru/6sem/books/Straustrup-Yazyk_programmirovaniya_c.pdf (издание поновее предлагаю искать самому).

    Полезные советы:
    1) Перестать слепо бродить по исходникам Огненной Лисы, выучить «C++» на более приемлемом уровне и продолжить бродить, но уже не слепо.

    Спасибо, что воспользовались нашим форумом!
    Ответить
      • В «PHP» много другой хуйни. Да он и сам, честно говоря, хуйня.
        Ответить
    • Спасибо
      вот я и учу С++, за 5 мин то не получается все выучить
      Ответить
      • нормальный компилятор должен выдавать 'string': undeclared identifier, а не портянку что у тебя
        каким древним говном ты пользуешся?
        Ответить
        • Кстати, посмотрим, что выводит разное несвежее говно.

          Borland:
          Warning W8057 a.cpp 5: Parameter 'c' is never used in function rec(const string,char)
          Error E2451 a.cpp 18: Undefined symbol 'mDocWrite' in function main()
          Warning W8012 a.cpp 25: Comparing signed and unsigned values in function main()
          Warning W8012 a.cpp 29: Comparing signed and unsigned values in function main()
          Warning W8012 a.cpp 29: Comparing signed and unsigned values in function main()
          Warning W8012 a.cpp 37: Comparing signed and unsigned values in function main()
          Warning W8012 a.cpp 47: Comparing signed and unsigned values in function main()


          Шланг:
          a.cpp:10:1: error: C++ requires a type specifier for all declarations
          main(){                                                                  //'main': identifier not found
          ^
          a.cpp:18:10: error: use of undeclared identifier 'mDocWrite'
          fin.open(mDocWrite); //'void std::basic_ifstream<char,std::char_traits<char>>::open(const char *,std::ios_base::open_mode)' : 
                   ^
          a.cpp:46:11: error: use of undeclared identifier 'mDocWrite'
          fout.open(mDocWrite);
                    ^


          Digital Mars:
          fin.open(mDocWrite); //'void std::basic_ifstream<char,std::char_traits<char>>::open(const char *,std::ios_base::open_mode)' : 
                            ^
          a.cpp(18) : Error: undefined identifier 'mDocWrite'
          fout.open(mDocWrite);
                             ^
          a.cpp(46) : Error: need explicit cast for function parameter 1 to get
          from: int 
          to  : char const *


          gcc:
          a.cpp: In function `int main()':
          a.cpp:18: error: `mDocWrite' undeclared (first use this function)
          a.cpp:18: error: (Each undeclared identifier is reported only once for each function it appears in.)
          Ответить
          • Напоследок Intel:
            a.cpp
            a.cpp(18): error: identifier "mDocWrite" is undefined
              fin.open(mDocWrite); //'void std::basic_ifstream<char,std::char_traits<char>>::open(const char *,std::ios_base::open_mode)' : 
                       ^
            
            a.cpp(23): error: no operator ">>" matches these operands
                        operand types are: std::ifstream >> std::string
              while(fin>>s)    //'s' : undeclared identifier, fatal error C1903: unable to recover from previous error(s); stopping compilation
                       ^
            
            a.cpp(35): error: no operator "+" matches these operands
                        operand types are: std::string + char
              								a=a+s[j];
              								   ^
            
            a.cpp(36): error: no operator "+" matches these operands
                        operand types are: std::string + const char [5]
              							a=a+"0.5*";
              							   ^
            
            a.cpp(38): error: no operator "+" matches these operands
                        operand types are: std::string + char
              								a=a+s[j];
              								   ^
            
            a.cpp(47): error: no operator "<<" matches these operands
                        operand types are: std::ofstream << std::string
              for (int i=0; i<mas.size(); ++i) fout<<mas[i]<<"\t";
                                                   ^

            И MSVC:
            a.cpp(10) : error C4430: отсутствует спецификатор типа - предполагается int. Примечание. C++ не поддерживает int по умолчанию
            a.cpp(18) : error C2065: mDocWrite: необъявленный идентификатор
            a.cpp(23) : error C2678: бинарный ">>": не найден оператор, принимающий левый операнд типа "std::ifstream" (или приемлемое преобразование отсутствует)
            ... огромный список кандидатов для перегрузки ...
                    при попытке сопоставить список аргументов "(std::ifstream, std::string)"
            a.cpp(23) : fatal error C1903: не удается восстановить после предыдущих ошибок; остановка компиляции
            Ответить
            • Забыл показать выхлоп Watcom:
              a.cpp(18): Error! E029: col(10) symbol 'mDocWrite' has not been declared
              a.cpp(23): Error! E157: col(10) left expression must be integral
              a.cpp(23): Note! N717: col(10) left operand type is 'std::ifstream (lvalue)'
              a.cpp(23): Note! N718: col(10) right operand type is 'std::basic_string<char,std::char_traits<char>,std::allocator<char>> (lvalue)'
              a.cpp(35): Error! E152: col(68) left operand is neither a pointer nor an arithmetic type
              a.cpp(35): Note! N717: col(68) left operand type is 'std::basic_string<char,std::char_traits<char>,std::allocator<char>> (lvalue)'
              a.cpp(35): Note! N718: col(68) right operand type is 'char (lvalue)'
              a.cpp(36): Error! E152: col(60) left operand is neither a pointer nor an arithmetic type
              a.cpp(36): Note! N717: col(60) left operand type is 'std::basic_string<char,std::char_traits<char>,std::allocator<char>> (lvalue)'
              a.cpp(36): Note! N718: col(60) right operand type is 'char [5] (lvalue)'
              a.cpp(38): Error! E152: col(68) left operand is neither a pointer nor an arithmetic type
              a.cpp(38): Note! N717: col(68) left operand type is 'std::basic_string<char,std::char_traits<char>,std::allocator<char>> (lvalue)'
              a.cpp(38): Note! N718: col(68) right operand type is 'char (lvalue)'
              a.cpp(47): Error! E157: col(38) left expression must be integral
              a.cpp(47): Note! N717: col(38) left operand type is 'std::ofstream (lvalue)'
              a.cpp(47): Note! N718: col(38) right operand type is 'std::basic_string<char,std::char_traits<char>,std::allocator<char>> (lvalue)'
              Ответить
        • Судя по формату сообщений об ошибках, у него Visual Studio. Осталось уточнить версию.
          Ответить
        • Если компилируешь плагины для какой-нибудь программы, порой приходится пользоваться древним компилятором хотя бы потому, что в разных версиях манглинг имён может быть разным.

          Я так и не смог определить, какой версией он пользуется. Доступные мне версии MSVC поняли тип string и без #include <string> (вероятно, его включают другие заголовочные файлы вроде iostream).
          Ответить
          • В общем, версии MSVC с 1998 года сами подхватывают <string>, если включить <iostream>, а в более старых нормальной библиотеки STL не было.

            Аж интересно стало, что за экзотика у топикстартера, в которой тип string не определился. Может быть, у него испорчено окружение и заголовочные файлы берутся из другого компилятора?
            Ответить
    • >> 18. ifstream::open() принимает строку — имя файла, а mDocWrite — это не строка.

      Переменная mDocWrite вообще не объявлена. Компилятор временно (чтобы не сломать парсер) считает, что у неё тип int.

      Вероятно, автор в целях тестирования выделил из какого-то кода фрагмент в отдельную программу, но забыл перенести все определения.
      Ответить
      • Судя по всему, автор продолжает писать что-то для Фаерфокса, и mDocWrite объявлена где-то ещё (cannot convert argument 1 from 'nsAutoPtr<nsHtml5Tokenizer>' to 'const wchar_t *'). А вот где объявлена и чем компилирует ТС — большой вопрос, да.
        Ответить
        • Супер!!!
          такие мозги киснут!
          Пользуюсь для компиляции MSVS 2013, + добавлены RUST and LLVM, по указанию к сборке Лисы.
          mDocWrite - это не строка , это я точно не туда прописал.
          Ответить
        • мне надо чтобы FF при загрузке файлов добавил в текст js выражение "*0,1". Вроде бы просто, но уже голову сломал, а сделать не могу.
          Ответить
        • это кусок кода
          nsresult
          nsHtml5Parser::Parse(const nsAString& aSourceBuffer,
                               void* aKey,
                               const nsACString& aContentType,
                               bool aLastCall,
                               nsDTDMode aMode) // ignored
          { 
          #include<iostream>
          #include<fstream>
          #include<vector>
          	  
          	  using namespace std;
          	  std::string
          	  string rec(const string str, char c) { return str; }
          
          	  void cer() {}
          		
          	  main() {
          		  string s, d = "TEXT", a;
          		  ifstream fin;
          		  vector<string> mas;
          		  fin.open(const nsAString& aSourceBuffer, const nsACString& aContentType);
          		  //if (fin.is_open()) cout<<"1";else	cout<<"0";
          		  while (fin >> s)
          		  {
          			  bool f = 0;
          			  for (int i = 0; i<s.size(); ++i)
          				  if (s[i] == d[0])
          				  {
          					  f = 1;
          					  for (int j = 0; j<s.size() && j<d.size(); ++j)
          						  if (d[j] != s[i + j]) f = 0;
          					  if (f)
          					  {
          						  a.clear();
          						  for (int j = 0; j<i; ++j)
          							  a = a + s[j];
          						  a = a + "0.1*";
          						  for (int j = i; j<s.size(); ++j)
          							  a = a + s[j];
          					  }
          				  }
          			  			  if (f) { mas.push_back("\n");mas.push_back(a);mas.push_back("\n"); }
          			  else mas.push_back(s);
          			  s = rec(s, '0');
          		  }
          		  ofstream fout;
          		  fout.open(const nsAString& aSourceBuffer, const nsACString& aContentType);
          		  for (int i = 0; i<mas.size(); ++i) fout << mas[i] << "\t";
          	  }
          
          	  nsresult rv;
            if (NS_FAILED(rv = mExecutor->IsBroken())) {
              return rv;
            }
            if (aSourceBuffer.Length() > INT32_MAX) {
              return mExecutor->MarkAsBroken(NS_ERROR_OUT_OF_MEMORY);
            }
          Ответить
          • nsresult
            nsHtml5Parser::Parse(const nsAString& aSourceBuffer,
                                 void* aKey,
                                 const nsACString& aContentType,
                                 bool aLastCall,
                                 nsDTDMode aMode) // ignored
            { 
            #include<iostream>
            #include<fstream>
            #include<vector>
            Зачем инклудишь хэдэры внутрь функции?
            std::string
            	  string rec(const string str, char c) { return str; }
            Что это? Ты видишь что ты пишешь?
            string rec(const string str, char c) { return str; }
            
            	  void cer() {}
            		
            	  main() {
            В C++ нет вложенных функций.
            fin.open(const nsAString& aSourceBuffer, const nsACString& aContentType);
            	fout.open(const nsAString& aSourceBuffer, const nsACString& aContentType);
            Убери объявления типов.

            Ты жестко путаешься, возьми что-нибудь попроще, и купи себе какую-нибудь книжку по программированию и почитай.
            Ответить
            • Хэдэры убрал, а std::string компилятор как-то хотел.
              Хорошо, это убрал. Как написать, книжка слабо помогает - практик нужен?
              Ответить
              • > using namespace std;
                забудь это сочетание, тем более в таких больших программах. Юзай полное имя – std::string вместо string, например std::string rec(const std::string str, char c).

                > практик нужен
                Идёшь на acmp.ru или что-то типа того и решай задачи.
                Ответить
                • нужен нормальный практик программист, мне далеко, даже если задачи решать
                  Ответить
              • Кто-нибудь, кого не затруднит, переведите всё, что обсуждалось выше, на "PHP". Я нихуя не понимаю.
                Ответить
              • как это можно использовать в моем случае
                NS_METHOD SetBlah(const nsAString &aBlah);
                   nsresult MyCode()
                   {
                     nsresult rv;
                
                     nsStringContainer sc;
                     rv = NS_StringContainerInit(sc);
                     if (NS_FAILED(rv))
                       return rv;
                
                     const char16_t kData[] = {'x','y','z','\0'};
                     rv = NS_StringSetData(sc, kData, sizeof(kData)/2 - 1);
                     if (NS_SUCCEEDED(rv))
                       rv = SetBlah(sc);
                
                     NS_StringContainerFinish(sc);
                     return rv;
                   }
                Ответить

Добавить комментарий

Где здесь C++, guest?!

    А не использовать ли нам bbcode?


    8