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 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 |
#include <limits> #include <iostream> #include <iomanip> #include <cstdlib> #include <string> #include <exception> #include <stdexcept> #include <map> #include <cstring> #include <new> using namespace std; #pragma warning(disable:4290) // Ошибка - аккаунт не существует class account_not_exist : public logic_error { public: account_not_exist() : logic_error("Аккаунт не существует") { }; }; // Валюты необходимые для задачи enum currencies { RUR, USD, EUR }; // Класс-деньги class money { public: // Конструкторы explicit money(double summa = 0.0, currencies currency = RUR) throw (invalid_argument); money(unsigned int int_part, unsigned char fract_part, currencies currency = RUR); // Тип валюты currencies getCurrency(); void setCurrency(currencies currency); private: // Целая часть суммы unsigned int _int_part; // Дробная часть суммы(копейки,центы,и т.д.) unsigned char _fract_part; // Тип валюты currencies _currency; unsigned long long smallChange() const; friend money operator+(const money& left, const money& right); friend money operator-(const money& left, const money& right) throw (invalid_argument); friend money operator*(const money& left, double right); friend money operator*(double left, const money& right); friend bool operator<(const money& left, const money& right); friend bool operator&g t;(const money& left, const money& right); friend wostream & operator<<(wostream& stream, const money& right); friend wistream & operator>>(wistream& stream, money& right); friend class exchanger; }; // Обменник class exchanger { public: // Меняет одну валюту на другую static money exchange(const money& summa, currencies currency); private: // Курсы обмена static map<currencies, double> _rates; }; // Инициализируем статический член нашего обменного класса typedef pair<currencies, double> rate_pair; rate_pair rates_arr[3] = {rate_pair(RUR, 1.0), rate_pair(USD, 30.1851), rate_pair(EUR, 43.4605)}; map<currencies, double> exchanger::_rates(rates_arr, rates_arr + sizeof (rates_arr) / sizeof (rate_pair)); // Для вывода типа валюты будем использовать следующие имена typedef pair<currencies, wstring> currency_name_pair; currency_name_pair cur rencies_names_arr[3] = {currency_name_pair(RUR, L"RUR"), currency_name_pair(USD, L"USD"), currency_name_pair(EUR, L"EUR")}; map<currencies, wstring> currency_names(currencies_names_arr, currencies_names_arr + sizeof (currencies_names_arr) / sizeof (currency_name_pair)); // Аккаунт class account { public: typedef unsigned int acc_num_type; // Конструктор account(const wstring& surname, acc_num_type account_num, double percent = 0.0, const money& cash = money(0.0)) throw (invalid_argument); // Меняет владельца void setOwner(const wstring& surname); // Возвращает владельца const wstring& getOwner() const; // Снимает деньги bool withdrawMoney(const money& summa); // Добавляет деньги void depositMoney(const money& summa); // Начисляет процент void thatInterest(); // Обмен валюты void exchangeTo(currencies currency); // Сумма money getCash() const; private: // Фамилия wstring _surname; // Номер счета acc_num_type _account_num; // Процент double _percent; // Сумма на счету money _cash; friend wostream & operator<<(wostream& stream, const account& right); }; // Выбор пользователя в меню enum user_choice { CREATE, CHANGE_OWNER, WITHDRAW_MONEY, DEPOSIT_MONEY, THAT_INTEREST, EXCHANGE_TO_RUR, EXCHANGE_TO_USD, EXCHANGE_TO_EUR, PRINT, EXIT }; user_choice menu(); void createAccount(account*&); void changeOwner(account*); void withdrawMoney(account*); void depositMoney(account*); void thatInterest(account*); void exchangeTo(account*, currencies); void printAccount(account*); wostream & operator<<(wostream& stream, const exception& right) { #pragma warning(disable:4996) const size_t len = mbstowcs(0,right.what(),0) + 1; try { wchar_t *buffer = new wchar_t[len]; mbstowcs(buffer, right.what(), len); stream<< buffer; delete[] buffer; } catch (bad_alloc&) { } return stream; } int main() { locale::global(locale("")); // Аккаунт account *acc = 0; bool is_exit = false; while (!is_exit) { try { switch (menu()) { case CREATE: createAccount(acc); break; case CHANGE_OWNER: changeOwner(acc); break; case WITHDRAW_MONEY: withdrawMoney(acc); break; case DEPOSIT_MONEY: depositMoney(acc); break; case THAT_INTEREST: thatInterest(acc); break; case EXCHANGE_TO_RUR: exchangeTo(acc, RUR); break; case EXCHANGE_TO_USD: exchangeTo(acc, USD); break; case EXCHANGE_TO_EUR: exchangeTo(acc, EUR); break; case PRINT: printAccount(acc); break; case EXIT: is_exit = true; break; } } catch (exception& ex) { wcout << ex << endl; } } if (acc) { delete acc; acc = 0; wcout << L"Счет уничтожен" << endl; } return 0; } wostream& line(wostream& stream) { stream << L"----------------------------------------------" << endl; return stream; } // Меню user_choice menu() { while (true) { wcout << line << L"Меню:" << endl << L"1 - Создать счет" << endl << L"2 - Сменить владельца" << endl << L"3 - Снять деньги" << endl << L"4 - Положить деньги:" << endl << L"5 - Начислить процент" << endl << L"6 - Обменять на RUR" << endl< br> << L"7 - Обменять на USD" << endl << L"8 - Обменять на EUR" << endl << L"9 - Напечатать информацию об аккаунте" << endl << L"0 - Выход" << endl << L"Сделайте свой выбор:"; wchar_t choice = wcin.get(); wcin.ignore(numeric_limits<streamsize>::max(), L'n'); wcout << line; switch (choice) { case L'0': return EXIT; case L'1': return CREATE; case L'2': return CHANGE_OWNER; case L'3': return WITHDRAW_MONEY; case L'4': return DEPOSIT_MONEY; case L'5': return THAT_INTEREST; case L'6': return EXCHANGE_TO_RUR; case L'7': return EXCHANGE_TO_USD; case L'8': return EXCHANGE_TO_EUR; case L'9': return PRINT; default: wcout << L"Будьте внимательней!" << endl; } } } template<class T> T input(wstring msg) { while (true) { wcout << msg; T result; wcin >> result; if (wcin.fail()) { wcout << L"Ошибочный ввод!" << endl; wcin.clear(); wcin.ignore(numeric_limits<streamsize>::max(), L'n'); } else { wcin.ignore(numeric_limits<streamsize>::max(), L'n'); return result; } } } // Создает аккаунт void createAccount(account*& acc) { wstring surname; wcout << L"Введите фамилию владельца счета:"; getline(wcin, surname); account::acc_num_type accountNum = input<account::acc_num_type > (L"Номер счета:"); double percent = input<double>(L"Процент:"); money summa = input<money > (L"Сумма денег на счету:"); try { account* new_acc = new account(surname, accountNum, percent, summa); if (acc) { delete acc; acc = 0; wcout << L"Старый аккаунт удален" << endl; } acc = new_acc; } catch (exception& ex) { wcout << ex << endl; } } // Меняет владельца void changeOwner(account* acc) { if (acc) { wstring surname; wcout << L"Введите фамилию нового владельца счета:"; getline(wcin, surname); acc->setOwner(surname); wcout << *acc << endl; } else { throw account_not_exist(); } } // Снимает деньги void withdrawMoney(account* acc) { if (acc) { money summa = input<money > (L"Какую сумму желаете снять?:"); summa.setCurrency(acc->getCash().getCurrency()); if (acc->withdrawMoney(summa)) { wcout << L"Операция прошла успешно" << endl << *acc << endl; } else { wcout << L"Невозможно снять требуемую сумму" << endl; } } else { throw account_not_exist(); } } // Ложит деньги на счет void depositMoney(account* acc) { if (acc) { money summa = input<money > (L"Какую сумму желаете положить?:"); summa.setCurrency(acc->getCash().getCurrency()); acc->depositMoney(summa); wcout << *acc << endl; } else { throw account_not_exist(); } } // Начисляет процент void thatInterest(account* acc) { if (acc) { acc->thatInterest(); wcout << *acc << endl; } else { throw account_not_exist(); } } // Обмен валют void exchangeTo(account* acc, currencies currency) { if (acc) { acc->exchangeTo(currency); wcout << *acc << endl; } else { throw account_not_exist(); } } // Вывод информации void printAccount(account* acc) { if (acc) { wcout << *acc << endl; } else { throw account_not_exist(); } } #pragma region Все, относящееся к class money money::money(double summa, currencies currency) throw (invalid_argument) { if (summa < 0) { throw invalid_argument("Сумма не может быть отрицательной"); } _int_part = static_cast<unsigned int> (summa); _fract_part = static_cast<unsigned char> ((summa - _int_part)*100); _currency = currency; } money::money(unsigned int int_part, unsigned char fract_part, currencies currency) { if (fract_part > 99) { throw invalid_argument("Количество мелочи не может быть больше 99"); } _int_part = int_part; _fract_part = fract_part; _currency = currency; } currencies money::getCurrency() { return _currency; } void money::setCurrency(currencies currency) { _currency = currency ; } inline unsigned long long money::smallChange() const { return _int_part * 100ULL + _fract_part; } // Оператор сложения money operator+(const money& left, const money& right) { if (left._currency != right._currency) { throw invalid_argument("Тип валюты не совпадает"); } unsigned int fract_part = left._fract_part + right._fract_part; return money(left._int_part + right._int_part + fract_part / 100, fract_part % 100,left._currency); } // Оператор вычитания money operator-(const money& left, const money& right) throw (invalid_argument) { if (left < right) { throw invalid_argument("Сумма слева не может быть меньше суммы справа. Результат операции не может быть отрицательным"); } if (left._currency != right._currency) { throw invalid_argument("Тип валюты не совпадает"); } unsigned long long resultSum = (left._int_part - right._int_part) * 100ULL + left._fract_part - right._fract_part; return money(static_cast<unsigned int> (resultSum / 100), resultSum % 100,left._currency); } // Оператор умножения(необходим для взятия процента) money operator*(const money& left, double right) { unsigned long long resultSum = static_cast<unsigned long long> ((left._int_part * 100 + left._fract_part) * right); return money(static_cast<unsigned int> (resultSum / 100), resultSum % 100, left._currency); } inline money operator*(double left, const money& right) { return right*left; } // Операторы сравнения bool operator<(const money& left, const money& right) { return left.smallChange() < right.smallChange(); } bool operator>(const money& left, const money& right) { return left.smallChange() > right.smallChange(); } / / Операторы ввода-вывода wostream & operator<<(wostream& stream, const money& right) { stream << right._int_part << L"," << setw(2) << setfill(L'0') << right._fract_part << L'(' << currency_names[right._currency] << L')'; return stream; } wistream & operator>>(wistream& stream, money& right) { double sum; stream >> sum; try { right = money(sum); } catch (exception&) { stream.setstate(ios::badbit); } return stream; } #pragma endregion Все, относящееся к class money money exchanger::exchange(const money& summa, currencies currency) { double rate = _rates[summa._currency] / _rates[currency]; money result = summa*rate; result._currency = currency; return result; } #pragma region Все, относящееся к class account account::account(const wstring& surname, acc_num_type account_num, double percent, const money& cash) throw (invalid_argument): _surname(surname), _account_num(account_num), _cash(cash) { if (percent < 0) { throw invalid_argument("Процент не может быть отрицательным"); } _percent = percent; } void account::setOwner(const wstring& surname) { _surname = surname; } const wstring& account::getOwner() const { return _surname; } bool account::withdrawMoney(const money& summa) { try { _cash = _cash - summa; return true; } catch (exception&) { return false; } } void account::depositMoney(const money& summa) { _cash = _cash + summa; } void account::thatInterest() { _cash = _cash * (1.0 + _percent / 100.0); } void account::exchangeTo(currencies currency) { _cash = exchanger::exchange(_cash, currency); } money account::getCash() const { return _cash; } wostream & operator<<(wostream& stream, const account& right) { stream << L"Информация об аккаунте:" << endl << L"Владелец:" << right._surname << endl << L"Номер счета:" << right._account_num << endl << L"Процент:" << fixed << setprecision(2) << right._percent << endl << L"Сумма:" << right._cash; return stream; } #pragma endregion Все, относящееся к class account |
Xmake 版本
2.7.4
操作系统版本和架构
centos 7.8
描述问题
按照如下步骤能稳定复现c程序的注释报错的bug:
1 、执行xmake create hello
2 、cd hello
3、xmake
4、打开xmake.lua修改为
add_rules("mode.debug", "mode.release")
set_languages("c89", "c++11")
target("hello")
set_kind("binary")
add_files("src/*.cpp")
add_files("src/*.c")
5、把main.cpp修改为main.c
6、随意复制一个c程序,只要是带注释即可
#include<unistd.h> //和fd有关[read() write() close()] lseek fork() execl() dup2() getpid()
#include<fcntl.h>//open()
#include<stdio.h>//perror()
#include<stdlib.h> //exit()
#include<dirent.h> //目录项操作:DIR opendir closedir readdir
#include<sys/wait.h> //wait()
#include<string.h>
int main(int argc,char *argv[])
{
int ret;
int fd[2];
pid_t pid;
char str[]="hello pipen";
char buf[1024]={0};
int status,w_pid;
//创建管道
ret=pipe(fd);
if(-1 == ret){
perror("pipe error");
}
pid=fork();
if(pid>0){//父进程
close(fd[0]);//关闭读端
dup2(fd[1],STDOUT_FILENO);//屏幕输出重定向到管道 写入
execlp("ls","ls",NULL);
perror("exclp error");
//因为使用exec函数族执行其他程序成功就不会回来了,所以下面就不用写了,只能指望隐式回收
// close(fd[1]);
// //阻塞等待子进程死亡防止僵尸进程
// w_pid=wait(&status);
// if(-1==w_pid){
// perror("wait error");
// exit(1);
// }
}else if(0==pid){//子进程
close(fd[1]);//关闭写端
dup2(fd[0],STDIN_FILENO);//从屏幕读取重定向到管道 读取
execlp("wc","wc","-l",NULL);
perror("exclp error");
//执行成功不再执行以下的
close(fd[0]);
}
return 0;
}
7、发现只要带注释的行都报错,有游离的»/»
8、发现是c标准的问题,改为c90后编译bug消失
9、但某些情况c89又能正常编译,忘了怎么触发的
期待的结果
报错如下
[xmk@VM-4-3-centos hello_xmake]$ xmake
[ 25%]: cache compiling.release src/main.c
error: src/main.c:19:5: error: expected expression before ‘/’ token
//创建管道
^
src/main.c:19:5: error: stray ‘345’ in program
src/main.c:19:5: error: stray ‘210’ in program
src/main.c:19:5: error: stray ‘233’ in program
src/main.c:19:5: error: stray ‘345’ in program
src/main.c:19:5: error: stray ‘273’ in program
src/main.c:19:5: error: stray ‘272’ in program
src/main.c:19:5: error: stray ‘347’ in program
src/main.c:19:5: error: stray ‘256’ in program
src/main.c:19:5: error: stray ‘241’ in program
src/main.c:19:5: error: stray ‘351’ in program
src/main.c:19:5: error: stray ‘201’ in program
src/main.c:19:5: error: stray ‘223’ in program
src/main.c:26:15: error: expected expression before ‘/’ token
if(pid>0){//父进程
> in src/main.c
warning: cannot match target(hello).add_files("src/*.cpp") at ./xmake.lua:6
工程配置
add_rules("mode.debug", "mode.release")
set_languages("c89", "c++11")
target("hello")
set_kind("binary")
add_files("src/*.cpp")
add_files("src/*.c")
- Forum
- Beginners
- error: stray ‘342’ in program
error: stray ‘342’ in program
trying a code for a simple game i downloaded. when i run it i get lines and lines of this error:
error stray ‘200’ in program (with different numbers)
— i’m using code::blocks, in case that matters….
what does this mean??
here are the first lines of the code. the first error (one in subject) points to line 36
|
|
thank you!!
Last edited on
Well, it is because there are “ and ” instead of » (note the slant!), and these characters are not valid.
………. it’s always the little things that matter
cin >> not <<
wow i guess there’s a lot wrong with this code.
I just got the same error doing something different now. In another example, i need to use this line:
#import «C:\Program Files\O2Gfxcore.dll»
does that mean the line is wrong or is the .dll library wrong?
Do you not notice the single backslash before fxcore.dll?
still getting the same error. I even moved the file to c: and used:
#import "C:\fxcore.dll"
and still same error
Could you copy and paste the error exactly?
Switch to forward slash /
instead of double-backslashes. It works on Win, and means you don’t have to worry about double-slashes.
Which compiler (and preprocessor) are you using? Does it recognise #import? It’s not part of the C++ standard.
the code (i tried include in place of import, same problem):
|
|
the error:
|
|
warning: #import is a deprecated GCC extension
Um…why are you using #import in that case?
Last edited on
Don’t use import. It seems that your preprocessor doesn’t recognise it.
Don’t #include
a dll file. It’s meaningless. #include
literally copies the entire file you want to include, and puts it into the place where you wrote #include
.
Do not #include
a dll file. I know I already said that, but I get the feeling saying it twice will help.
Why are you trying to #include
a dll file? I think you must have misunderstood what a dll file is.
Last edited on
Topic archived. No new replies allowed.