Hello forum,
I seem to be having trouble compiling this program. . I get 3 different errors for the same 2 lines.
1) [Error] stray ‘226’ in program
2) [Error] ‘(pay + ((long long unsigned int)(((long long unsigned int)count) * 32ull)))->EmployeePay::gross’ cannot be used as a function
3) [Error] expected ‘)’ before numeric constant
*Lines are underlined and bolded
#include <iostream>
#include <iomanip>
using namespace std;
const float CONST_STATE_TAX = 0.05;
const float CONST_FED_TAX = 0.15;
const float CONST_UNION_FEES = 0.02;
const int NUM_EMPLOYEES = 5;
const int NAME_LENGTH = 20;
const int ID_LENGTH = 6;
typedef char String[NAME_LENGTH];
struct EmployeeInfo{
String firstname;
char middleinitial;
String lastname;
String idnumber;
};
struct EmployeePay{
float rate;
float overtime;
float gross;
float state_tax;
float fed_tax;
float union_fees;
float net;
float hours;
};
void Input(EmployeeInfo[], EmployeePay[]);
void Calculate(EmployeePay[]);
void Output(EmployeeInfo[], EmployeePay[]);
void OutputFile(EmployeeInfo[], EmployeePay[]);
int main()
{
EmployeeInfo info[NUM_EMPLOYEES];
EmployeePay pay[NUM_EMPLOYEES];
Input(info, pay);
Calculate(pay) ;
Output(info, pay);
OutputFile(info, pay);
return 0;
}
void Input(EmployeeInfo info[], EmployeePay pay[])
{
for (int count; count < NUM_EMPLOYEES; count++)
{
cout << «Please enter student #» << (count + 1) << » first name: «;
cin.getline(info[count].firstname, NAME_LENGTH);
cout << «Please enter student #» << (count + 1) << » middle initial: «;
cin >> info[count].middleinitial;
cout << «Please enter student #» << (count + 1) << » last name: «;
cin.getline(info[count].lastname, NAME_LENGTH);
cout << «Please enter student #» << (count + 1) << » id number: «;
cin.getline(info[count].idnumber, NAME_LENGTH);
cout << «Please enter student #» << (count + 1) << » hourly pay rate: «;
cin >> pay[count].rate;
while (pay[count].rate < 0)
{
cout << «Invalid hourly pay. You must enter a rate greater than ‘0’.»
<< » Enter a rate: «;
cin >> pay[count].rate;
}
cout << «Please enter student #» << (count + 1) << » total hours worked: «;
cin >> pay[count].hours;
while (pay[count].hours > 60 || pay[count].hours < 40)
{
cout << «Invalid hours worked. You cannot work more than 60 or»
<< » less than 40 hours per week. Enter hours worked: «;
cin >> pay[count].hours;
}
cin.ignore();
}
}
void Calculate(EmployeePay pay[])
{
for (int count; count < NUM_EMPLOYEES; count++)
{
pay[count].overtime = ((pay[count].hours) – 40.00);
pay[count].gross = ((pay[count].rate * 40.00) + ((pay[count].overtime) * (pay[count].rate * 1.50)));
pay[count].state_tax = (CONST_STATE_TAX * pay[count].gross);
pay[count].fed_tax = (CONST_FED_TAX * pay[count].gross);
pay[count].union_fees = (CONST_UNION_FEES * pay[count].gross);
pay[count].net = ((pay[count].gross) – ((pay[count].state_tax) + (pay[count].fed_tax) + (pay[count].union_fees)));
}
}
void Output(EmployeeInfo info[], EmployeePay pay[])
{
cout <<«Student Records » << endl;
cout << setfill(‘=’) << setw(143) << » << setfill(‘ ‘) << endl;
cout << left << setw(13) << «First Name» << setw(13) << «Middle Initial» << setw(13) << «Last Name» << setw(13)
<< «Id Number» << setw(13) << «Rate» << setw(13) << «Overtime» << setw(13) << «Gross» << setw(13) << «State Tax»
<< setw(13) << «Fed Tax» << setw(13) << «Union Fees» << setw(13) << «Net» << endl;
cout << setfill(‘=’) << setw(143) << » << setfill(‘ ‘) << endl;
for (int count; count < NUM_EMPLOYEES; count++)
{
cout << setw(13) << info[count].firstname;
cout << setw(13) << info[count].middleinitial;
cout << setw(13) << info[count].lastname;
cout << setw(13) << info[count].idnumber;
cout << setw(13) << pay[count].rate;
cout << setw(13) << pay[count].overtime;
cout << setw(13) << pay[count].gross;
cout << setw(13) << pay[count].state_tax;
cout << setw(13) << pay[count].fed_tax;
cout << setw(13) << pay[count].union_fees;
cout << setw(13) << pay[count].net;
cout << setfill(‘-‘) << setw(143) << » << setfill(‘ ‘) << endl;
}
}
The stray character is the wrong sort of ‘-‘.
The usual cause is using a word-processor rather than a plain text editor (or an editor designed for writing code).
The usual minus sign typed on the keyboard is — but the code contains – instead. The first is ASCII code 45, the second ASCII code 226. If you use a word processor, it «helpfully» changes the characters that you type into some other completely different (but perhaps visually similar) character.
Solution.
1. use a suitable code or text editor
2. change this:
pay[count].overtime = ((pay[count].hours) –
40.00);
to this:
pay[count].overtime = ((pay[count].hours) -
40.00);
While we’re here, there are lots of unnecessary parentheses around everything here, the code works correctly (and is easier to read) without them,
pay[count].overtime = pay[count].hours - 40.00;
That same comment applies to all the lines in that part of the code.
The main thing to remember is that multiplication and division take precedence over addition and subtraction
For example, 2 * 3 + 4 * 5
will be interpreted as (2 * 3) + (4 * 5)
Generally, it’s not necessary to include to use parentheses unless you want to change the default interpretation.
One more error. This function has a prototype declaration:
void OutputFile(EmployeeInfo[], EmployeePay[]);
but the actual function body is not defined.
Last edited on
@Chervil I appreciate the quick and detailed response. Thank you
Я написал следующий код. это реализовать двусвязный список. Но вылезли ошибки.
while(x==1); // This line showed errors
return 1;
Ошибки:
DoublyLinkedList.c: In function `main':
DoublyLinkedList.c:194: error: stray '226' in program
DoublyLinkedList.c:194: error: stray '128' in program
DoublyLinkedList.c:194: error: stray '156' in program
DoublyLinkedList.c:194: error: `The' undeclared (first use in this function)
DoublyLinkedList.c:194: error: (Each undeclared identifier is reported only once
DoublyLinkedList.c:194: error: for each function it appears in.)
DoublyLinkedList.c:194: error: parse error before "list"
DoublyLinkedList.c:194: error: stray '226' in program
DoublyLinkedList.c:194: error: stray '128' in program
DoublyLinkedList.c:194: error: stray '157' in program
Что за случайная ошибка? Что это за случайные числа?
2 ответы
Я вырезал и вставил код из документа Microsoft Word. Знак минус отображался моим текстовым редактором, но на самом деле это было восьмеричное значение 226 или шестнадцатеричное 96. Знак минус должен был быть шестнадцатеричным 2D. Я мог видеть это, когда открывал свой код как двоичный файл — восьмеричное число 226 отображалось в листинге ASCII как блок.
ответ дан 06 мар ’21, в 12:03
ВЕСЬ Ваш DoublyLinkedList.c
кажется, содержит текст, который не является допустимым C. Эти числа являются восьмеричными значениями символов, которые недопустимы в программе C.
Если вы хотели поместить описательный комментарий в начало исходного файла, убедитесь, что каждая строка вашего комментария начинается с //
.
while(x==1);
это цикл while с пустым телом (т.е. последняя точка с запятой). Если x
равно 1, ваша программа будет бесконечно зацикливаться.
ответ дан 02 мая ’14, 21:05
Не тот ответ, который вы ищете? Просмотрите другие вопросы с метками
c
or задайте свой вопрос.
Вопросы по учебнику С… (Плавно из одного вопроса получилось несколько)
Модератор: Модераторы разделов
-
Boron
- Сообщения: 197
Вопросы по учебнику С…
Прошу меня не банить и удалить тему (если она будет мешаться).
Как запустить эту программу, зависит от системы, которую вы используете. Так, в операционной системе UNIX необходимо сформировать исходную программу в файле с именем, заканчивающимся символами «.c», например в файле hello.c, который затем компилируется с помощью команды
cc hello.c
Если вы все сделали правильно — не пропустили где-либо знака и не допустили орфографических ошибок, то компиляция пройдет ”молча” и вы получите файл, готовый к исполнению и названный a.out. Если вы теперь запустите этот файл на выполнение командой
a.out
программа напечатает
Hello, world
Как вы поняли, я решил начать учить язык С, но вот беда — не знаю, как запустить файл a.out. Помогите, пожалуйста!
-
Boron
- Сообщения: 197
Re: Вопросы по учебнику С…
Сообщение
Boron » 08.06.2006 00:54
Столкнулся с проблемой
#include <stdio.h>
/* печать таблицы температур по фаренгейту и цельсию для fahr = 0,20,…,300*/main()
{
int fahr, celsius;
int lower,upper,step;lower=0;/*нижняя граница таблицы температур*/
upper=300;/*верхняя граница таблицы температур*/
step=20;/*шаг*/fahr=lower
while(fahr <= upper){
celsius=5*(fahr-32)/9;
printf(«%dt%dn»,fahr,celsius);
fahr=fahr+step}
}
Писал все, как написано в учебнике, но почему-то в консоле выдается следующее:
boron@linux:~/Desktop/c> cc hello.c
hello.c: In function ‘main’:
hello.c:14: error: syntax error before ‘while’
hello.c:17: error: syntax error before ‘}’ token
hello.c:17:16: warning: no newline at end of file
Кто-нибудь может сказать в чем дело? Делал разные вариации скобок в строках 14 и 17 — не помогло. Пытался как их удалить, так и перенести в другие строчки. По поводу 17:16 строки я вообще не понимаю, что за новая линия у конца файла?
-
iAm
- Сообщения: 220
- ОС: Gentoo
Re: Вопросы по учебнику С…
Сообщение
iAm » 08.06.2006 01:09
1. Вы в 16-й строке (fahr=lower) забыли поставить в конце ;.
2. Сорец должен заканчиваться пустой строкой. То есть просто нажмите <Enter> в конце файла.
diesel, пока писал, уже Вы ответили.
-
Boron
- Сообщения: 197
Re: Вопросы по учебнику С…
Сообщение
Boron » 08.06.2006 01:11
Точно! Спасибо! Невнимательность… Но остальные сообщения не убрались
ИСПРАВЛЕНО:
boron@linux:~/Desktop/c> cc hello.c
hello.c: In function ‘main’:
hello.c:17: error: syntax error before ‘}’ token
А что самое странное: я скопировал полностью текст кода из учебника (он в электронном виде) и вставил заместо своего, и тогда вообще пишеться:
boron@linux:~/Desktop/c> cc hello.c
hello.c: In function ‘main’:
hello.c:17: error: stray ‘226’ in program
hello.c:17: error: stray ‘128’ in program
hello.c:17: error: stray ‘156’ in program
hello.c:17: error: syntax error before ‘%’ token
hello.c:17: error: stray ‘’ in program
hello.c:17: error: stray ‘’ in program
hello.c:17: error: stray ‘226’ in program
hello.c:17: error: stray ‘128’ in program
hello.c:17: error: stray ‘157’ in program
hello.c:20:2: warning: no newline at end of file
Вот и поучился, плин . Я сомневаюсь, что в учебнике что неправильно написано — может какую программу установить надо? Просто при установке дистрибутива я все оставлял «как есть» и не выбирал какие программы мне необходимо устанавливать, а какие нет (просто только влез в мир Юникс).
И еще — лишние/недостающие пробелы учитываются? Просто к примеру у меня отличие кода, по сравнению с учебником, где написано:
celsius = 5 * (fahr-32) / 9;
я пишу:
celsius=5*(fahr-32)/9;
P.S. Тему переименовал, т.к. заголовок уже носит несколько иное описание постов
-
iAm
- Сообщения: 220
- ОС: Gentoo
Re: Вопросы по учебнику С…
Сообщение
iAm » 08.06.2006 01:25
1. Исправьте
на
.
2. Ничего доустанавливать не нужно.
3.
(Boron @ Jun 8 2006, в 08:11) писал(а):И еще — лишние/недостающие пробелы учитываются?
Все и так работать будет, но в будущем лучше с пробелами писать.
Стиль, знаете ли. Плюс могу привести пример, когда такое написание может вызвать ошибку в программе.
-
Boron
- Сообщения: 197
Re: Вопросы по учебнику С…
Сообщение
Boron » 08.06.2006 01:29
Спасибо всем огромное, все заработало! Буду разбираться теперь над значением команд!
iAm, верю наслово, что это может вызвать ошибку в программе, поэтому и спросил … Чтобы привыкать к пробелам, сразу.
-
fatboy
- Сообщения: 156
- ОС: Zenwalk Linux, Windows XP
Re: Вопросы по учебнику С…
Сообщение
fatboy » 08.06.2006 04:07
Я, блин и не заметил что между step и } нет ; Сразу назрел совет:
Код будет лучше читаться если писать примерно так:
Код: Выделить всё
while(fahr <= upper){
celsius=5*(fahr-32)/9;
printf("%dt%dn",fahr,celsius);
fahr=fahr+step;
}
(Я так пишу )
Так видно где какой блок заканчивается. Но это ИМХО. Вообще — вопрос стилей, а их только общепризнанных штуки 4 или 5.
Zenwalk 4.0
TOSHIBA Satellite A100
-
void_false
- Сообщения: 198
- Статус: Sergeant of Operations, IDF
- ОС: Arch x86_32
- Контактная информация:
Re: Вопросы по учебнику С…
Сообщение
void_false » 08.06.2006 11:33
А что самое странное: я скопировал полностью текст кода из учебника (он в электронном виде) и вставил заместо своего, и тогда вообще пишеться:
Частенько в электронных изданиях напечатанные символы не соответствуют реальности. То есть вместо (‘) напечатано (`) итд. Так что лучше переписывать с нуля или смотреть прилагающиеся листинги (если таковые есть вообще)
-
Boron
- Сообщения: 197
Re: Вопросы по учебнику С…
Сообщение
Boron » 08.06.2006 15:38
void_false, ну я все с нуля и пишу, чтобы лучше запомнить команды
А вообще, мне вот что интересно:
На языке С пишуться только консольные программы или для графической среды тоже можно (в свое время узнаю, если не заброшу учебники, но все-таки хотелось бы знать)
-
aLexx programmer
- Сообщения: 985
- Статус: Турук-Макто
- ОС: Gentoo -> Ubuntu
Re: Вопросы по учебнику С…
Сообщение
aLexx programmer » 08.06.2006 15:52
(Boron @ Jun 8 2006, в 15:38) писал(а):На языке С пишуться только консольные программы или для графической среды тоже можно (в свое время узнаю, если не заброшу учебники, но все-таки хотелось бы знать)
Можно. Смотри в сторону gtk.
-
georgy_sh
- Сообщения: 1172
- Статус: thermonuclear…
- ОС: GNU/Linux
Re: Вопросы по учебнику С…
Сообщение
georgy_sh » 08.06.2006 16:30
Boron писал(а): ↑
08.06.2006 15:38
void_false, ну я все с нуля и пишу, чтобы лучше запомнить команды
А вообще, мне вот что интересно:
На языке С пишуться только консольные программы или для графической среды тоже можно (в свое время узнаю, если не заброшу учебники, но все-таки хотелось бы знать)
На языке С пишется огромное количество софта под Linux. Вообще-то на С можно написать, ИМХО, практически любую вещь (в пределах разумного).
Я же сам предпочитаю ООП — поэтому пишу на C++.
-
elide
- Бывший модератор
- Сообщения: 2421
- Статус: Übermensch
- ОС: лялих
Re: Вопросы по учебнику С…
Сообщение
elide » 08.06.2006 17:09
предпочитаю ООП — поэтому пишу на C++
вспомнилось…
Код: Выделить всё
"Я придумал термин "объектно-ориентированный", и вот что я вам скажу, я не имел ввиду С++."
-- Алан Кей, OOPSLA '97
(:
слава роботам!
-
Alxn1
- Сообщения: 402
- Статус: Красноглазик со стажем
- ОС: Mavericks
- Контактная информация:
Re: Вопросы по учебнику С…
Сообщение
Alxn1 » 08.06.2006 17:37
elide писал(а): ↑
08.06.2006 17:09
Код: Выделить всё
"Я придумал термин "объектно-ориентированный", и вот что я вам скажу, я не имел ввиду С++." -- Алан Кей, OOPSLA '97
(:
IMHO, в рамках ООП можно писать и на С и на Паскале, но удобнее и приятнее — на С++ или на чём-нибудь, что поддерживает данную методологию.
-
Andrew S
- Сообщения: 225
- Статус: экспериментатор
- ОС: Conrad-Gentoo
Re: Вопросы по учебнику С…
Сообщение
Andrew S » 08.06.2006 19:37
fatboy писал(а): ↑
08.06.2006 04:07
Я, блин и не заметил что между step и } нет ;
Сразу назрел совет:
Код будет лучше читаться если писать примерно так:
Код: Выделить всё
while(fahr <= upper){ celsius=5*(fahr-32)/9; printf("%dt%dn",fahr,celsius); fahr=fahr+step; }
(Я так пишу
)
Так видно где какой блок заканчивается. Но это ИМХО. Вообще — вопрос стилей, а их только общепризнанных штуки 4 или 5.
Для новичков: этот стиль описан файле в /usr/src/linux/Documentation/CodingStyle (если конечно исходники ядра установлены). Очень полезно почитать и использовать
-
Sfunx
- Сообщения: 47
Re: Вопросы по учебнику С…
Сообщение
Sfunx » 09.06.2006 11:43
Boron писал(а): ↑
08.06.2006 15:38
На языке С пишуться только консольные программы или для графической среды тоже можно (в свое время узнаю, если не заброшу учебники, но все-таки хотелось бы знать)
Согласно принципам написания программ на ЛЮБОМ языке можно писать ЛЮБЫЕ программы. Вопрос только в трудозатратах и количестве имеющихся библиотек.
Для графики я использовал под Linux wxGTK. Если интересно могу выложить прогу на этой байде. для рисования GTK окошек-кнопок можно использовать Glade2, например.
-
elide
- Бывший модератор
- Сообщения: 2421
- Статус: Übermensch
- ОС: лялих
Re: Вопросы по учебнику С…
Сообщение
elide » 09.06.2006 14:11
boombick
а ну ка расскажи нам про использование QT в голых сях (:
Sfunx
Согласно принципам написания программ на ЛЮБОМ языке можно писать ЛЮБЫЕ программы
хм…. интересно, как может выглядеть программа, скажем, рендеринга svg графики, написанная на brainfuck…..
слава роботам!
-
Alxn1
- Сообщения: 402
- Статус: Красноглазик со стажем
- ОС: Mavericks
- Контактная информация:
Re: Вопросы по учебнику С…
Сообщение
Alxn1 » 09.06.2006 15:00
elide писал(а): ↑
09.06.2006 14:11
boombick
а ну ка расскажи нам про использование QT в голых сях (:
А по-моему можно. Вроде какая-то обёртка была. Правда, как называется не помню, на sourceforge.net можно поискать, лень только…
-
Alxn1
- Сообщения: 402
- Статус: Красноглазик со стажем
- ОС: Mavericks
- Контактная информация:
Re: Вопросы по учебнику С…
Сообщение
Alxn1 » 09.06.2006 16:14
elide писал(а): ↑
09.06.2006 15:52
это наверное была обертка для gtk в С++ (:
Неа, не оно. Смотрим на QTC в составе Qt# (http://qtcsharp.sourceforge.net/). Вот оно. Правда, сам не пользовал никогда
-
fatboy
- Сообщения: 156
- ОС: Zenwalk Linux, Windows XP
Re: Вопросы по учебнику С…
Сообщение
fatboy » 09.06.2006 22:45
Мысли «вслух».
nerezus писал(а): ↑
08.06.2006 23:12
а про подобную расстановку(точнее нерасстановку пробелов) там так и написано?
т е. fahr+=step вместо fahr += step
Читал как-то книгу Хэзфилда и Кирби «Искусство программирования на С» — интересная книжулька, но для людей уже знакомых с С — так там приводится несколько стилей расстановки именно фигурных скобок и примеры различных управляющих структур, оформленных в разных стилях. Так же как один из вопросов — отступ в блоке от начала строки. О пробелах между операциями и операндами везде где встречаю так только в виде совета.
/Мысли «вслух».
to Boron:
Тот кусочек кода, что я написал, не «правильное» оформление а один из стилей оформления (Да и то я его немного под себя подогнал ). Так что лучше всего найти документ именно по стилям и определится с тем какой Вам больше нравится и удобно читается.
Zenwalk 4.0
TOSHIBA Satellite A100
-
Sfunx
- Сообщения: 47
Re: Вопросы по учебнику С…
Сообщение
Sfunx » 11.06.2006 10:22
elide писал(а): ↑
09.06.2006 14:11
хм…. интересно, как может выглядеть программа, скажем, рендеринга svg графики, написанная на brainfuck…..
А это не суть важно. Я говорю о «принципиальной возможности». Можно хоть на машине Тьюринга написать рендеринг. Вопрос только в том, какой язык для какой задачи удобнее.
Кстати, сам видел одну программистку, которая на FoxPro писала хрень для работы с нестандартной аппаратурой. Программа была конечно — п..ц, но работала
- Forum
- General Programming Boards
- C++ Programming
- Please Help!!!
Thread: Please Help!!!
-
06-24-2005
#1
Registered User
I gota problem.
Plese help me to solve.
temperature.cpp: In function `double FtoC(double)’:
temperature.cpp:11: stray ‘226’ in program
temperature.cpp:11: parse error before numeric constant
temperature.cpp: In function `double KtoC(double)’:
temperature.cpp:15: stray ‘226’ in program
temperature.cpp:15: parse error before numeric constantThanks.
-
06-24-2005
#2
*this
post the code, it will be easier to spot a problem
-
06-24-2005
#3
Registered User
At a guess, you’ve managed to get some strange characters into your temperature.cpp file. If you’ve used an editor like Microsoft word to edit your file, you need to save your file as a text file. Usually, you will be better off using a straight text editor or a program designed specifically for editing source code.
-
06-24-2005
#4
Registered User
F1uT3_Code
Code:
temperature.h #ifndef TEMPERATURE_H #define TEMPERATURE_H double FtoC(double); // c = (5/9) * (f �32) //Function FtoC() return temperature by converting Fahrenhiet to Celsius double KtoC(double); // c = k � 273.2 //Function KtoC() return temperature by converting Kelvin to Celsius /* double CtoK(double); // k = c + 273.2 //Function CtoK() return temperature by converting Celsius to Kelvin double CtoF(double); // f = (9/5) * c + 32 //Function CtoF() return temperature by converting Celsius to Fahrenhiet */ void tableheading(); //Create Table Heading #endif DONE BY F1uT3
Code:
temperature.cpp #include"temperature.h" #include <iostream> #include <iomanip> using std::cout; using std::setw; //Function Definitions //Functions of temperatures by using Celsius as a base for converting to Fahrenheit and Kelvin. /* double FtoC(double f) // Function for converting Fahrenheit to Celsius { return (f-32)*5.0/9; } double KtoC(double k) // Function for converting Kelvin to Celsius { return (k�273.2); }*/ double CtoK(double c) // Function for converting Celsius to Kelvin { return c+273.2; } double CtoF(double c) // Function for converting Celsius to Fahrenheit { return 9.0/5*c+32; } void tableheading() { //Print a table heading cout<<"******************************"; cout<<setw(8)<<"nCelsius|" <<setw(12)<<"Fahrenheit|" <<setw(8)<<" Kelvin |" <<setw(8)<<"Celsius|" <<setw(8)<<"Celsius|" <<setw(8)<<"Celsius|"; cout<<setw(8)<<"nC_Base|" <<setw(12)<<"C_Base2F |" <<setw(8)<<"C_Base2K|" <<setw(12)<<"K_Base2C|" <<setw(12)<<"F_Base2C|" <<setw(8)<<"C_Base|"; cout<<"n******************************n"; } DONE BY F1uT3
Code:
temptable.cpp /*Write a program to display a nice table of temperatures showing temperature values of Celsius, Kelvin and Fahrenheit for Celsius values of ranging from �50 to + 150 utilizing the library.*/ #include"temperature.h" #include <iostream> #include <iomanip> using std::cout; using std::cin; using std::endl; using std::setw; using std::setprecision; using std::fixed; int main() { //========Declare Variables======== double c,f,k,c2f,c2k,f2c,k2c; double lowest_c=-50; double highest_c=150; double step_size=1; //========Display A Welcome Statement======== cout<<"TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT"<<endl; cout<<"-------- This is a program , a conversion table of temperatures(C,F,K). --------"<<endl; cout<<"TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT"<<endl; //========Display A Table of Temperatures======== tableheading(); for(c=lowest_c ; c<=highest_c ; c+=step_size) { cout<<setw(5)<<setprecision(0)<<c; c2f=CtoF(c); cout<<setw(12)<<fixed<<setprecision(2)<<c2f; c2k=CtoK(c); cout<<setw(10)<<fixed<<setprecision(2)<<c2k; /*for(k=223.20 ; k<=423.20 ; k+=step_size) { k2c=KtoC(k); cout<<setw(10)<<fixed<<setprecision(2)<<k2c; } for(f=102.00 ; f<=302.00 ; f+=step_size) { f2c=FtoC(f); cout<<setw(12)<<fixed<<setprecision(2)<<f2c; } cout<<setw(5)<<setprecision(0)<<c;*/ if(c==-10 || c==30 || c==70 || c==110) //Fix the number shown every pages { cout<<"nPress Enter to continue ..."; cin.get(); //get Enter key to continue tableheading(); } } return 0; } DONE BY F1uT3
Last edited by F1uT3; 06-24-2005 at 12:56 PM.
-
06-24-2005
#5
Registered User
If any my codes are not right,plz tell me what the wrong is ?
Thank you.
-
06-24-2005
#6
Cat without Hat
Can you upload temperature.cpp instead of copying it? The issue is that there’s an invalid character somewhere in there, but the copy & paste operation seems to have made it disappear.
All the buzzt!
CornedBee
«There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code.»
— Flon’s Law
-
06-24-2005
#7
Anti-Poster
Alternately, you could delete those functions from your source file, and then copy and paste them back into the file from here.
If I did your homework for you, then you might pass your class without learning how to write a program like this. Then you might graduate and get your degree without learning how to write a program like this. You might become a professional programmer without knowing how to write a program like this. Someday you might work on a project with me without knowing how to write a program like this. Then I would have to do you serious bodily harm. — Jack Klein
-
06-24-2005
#8
Registered User
…….
Last edited by F1uT3; 06-24-2005 at 12:42 PM.
-
06-24-2005
#9
Cat without Hat
Some of your — signs are actually – signs (wide dashes) — probably because Word or a similar program auto-converted them. Don’t use word processors for programming.
All the buzzt!
CornedBee
«There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code.»
— Flon’s Law
-
06-24-2005
#10
and the hat of int overfl
What he said
Code:
72 65 74 75 72 6e 20 20 28 6b 96 32 37 33 2e 32 >return (k.273.2<
That — sign isn’t really a minus.
-
06-24-2005
#11
Registered User
I use «EditPlus» for Programming and MSYS to COmpile and Run
-
06-24-2005
#12
Registered User
I don’t understand CornedBee’s and Salem’s
-
06-24-2005
#13
Registered User
They are saying the — character in your code is not a normal dash it is a different character that your compiler doesn’t recognize. Wherever you copied your code from, or wherever you typed it in is using the wrong character for the minus sign. Use a different editor.
One solution is to re-type all your minus signs in an editor that will actually only put regular dashes.
-
06-24-2005
#14
and the hat of int overfl
> Some of your — signs are actually – signs (wide dashes) —
You often get this problem when you copy/paste code which has been mangled to make it HTML-friendly.> @ F1uT3
Just retype the minus signs on lines 11 and 13 (like the error messages say)
-
06-24-2005
#15
Registered User
Thank you all , I already understand ,and now I can compile it .
Thanks again.
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
- Forum
- The Ubuntu Forum Community
- Ubuntu Specialised Support
- Development & Programming
- Packaging and Compiling Programs
- Can’t compile simple C++ prog?
-
Can’t compile simple C++ prog?
greetings,
im trying to learn c++ and was working through a tutorial and it wanted me to make a simple «hello world» program. when i went to compile it gave errors.
Code:
#include <iostream> int main() { cout<<"HEY, you, I'm alive! Oh, and Hello World!"; return 0; }
and i got these errors:
Code:
root@error:/home/mark/Programming# g++ helloworld.cpp helloworld.cpp: In function �int main()�: helloworld.cpp:5: error: �cout� was not declared in this scope
Code:
root@error:/home/mark/Programming# gcc helloworld.cpp helloworld.cpp: In function �int main()�: helloworld.cpp:5: error: �cout� was not declared in this scope
Code:
root@error:/home/mark/Programming# bcc helloworld.cpp ld86: cannot open input file crt0.o
i have build-essential installed, also have bcc installed. i cant seem to find any info on such an error, the tutorials didnt speak of it either. what now? i know i cant continue learning c++ if i cant even compile a simple hello world prog.
-
Re: Can’t compile simple C++ prog?
You must be using an old book. It’s «std::cout» now. You’ll understand once you get to namespaces.
-
Re: Can’t compile simple C++ prog?
alternately, you could just add
after the #include.
-
Re: Can’t compile simple C++ prog?
Code:
#include <iostream> using namespace std; int main() { cout << "Hello world!" << endl; }
Or, alternatively:
Code:
#include <iostream> using std::cout; using std::endl; int main() { cout << "Hello world!" << endl; }
If you’re just starting out with C++, I recommend Bruce Eckel’s Thinking in C++ series of books. He has generously made them available for free download here.
-
Re: Can’t compile simple C++ prog?
did you use gcc to compile the program. Use g++ to compile and it will work
-
Re: Can’t compile simple C++ prog?
Originally Posted by vinay_lakhanpal
did you use gcc to compile the program. Use g++ to compile and it will work
Nah, he just forgot to ‘add’ the std libary
-
Re: Can’t compile simple C++ prog?
i’ll start asking sorry for this but i still don’t understand my problem.. im running under ubuntu dapper 6.06.1 and when i try to compile a simple c++ program i get this errors:
gcc: prova: Nessun file o directory
prova.c: In function �main�:
prova.c:8: error: stray �226� in program
prova.c:8: error: stray �128� in program
prova.c:8: error: stray �156� in program
prova.c:8: error: �Un� undeclared (first use in this function)
prova.c:8: error: (Each undeclared identifier is reported only once
prova.c:8: error: for each function it appears in.)
prova.c:8: error: syntax error before �solo�
prova.c:8: error: stray �� in program
prova.c:8: error: stray �226� in program
prova.c:8: error: stray �128� in program
prova.c:8: error: stray �157� in program
prova.c:11: error: stray �226� in program
prova.c:11: error: stray �128� in program
prova.c:11: error: stray �156� in program
prova.c:11: error: �Sono� undeclared (first use in this function)
prova.c:11: error: syntax error before �il�
prova.c:11: error: stray �� in program
prova.c:11: error: stray �226� in program
prova.c:11: error: stray �128� in program
prova.c:11: error: stray �157� in program
prova.c:13: error: stray �226� in program
prova.c:13: error: stray �128� in program
prova.c:13: error: stray �156� in program
prova.c:13: error: stray �226� in program
prova.c:13: error: stray �128� in program
prova.c:13: error: stray �157� in program
prova.c:15: error: stray �226� in program
prova.c:15: error: stray �128� in program
prova.c:15: error: stray �156� in program
prova.c:15: error: stray �� in program
prova.c:15: error: stray �226� in program
prova.c:15: error: stray �128� in program
prova.c:15: error: stray �157� in programyes unfortunately its italian but u should still understand well the problem.. the code in prova.c is:
#include <stdio.h>
#include <stdlib.h>main()
{
int pid;
printf(�Un solo processo finoran�);
pid = fork();
if (pid==0)
printf(�Sono il figlion�);
else if (pid > 0)
printf(�Sono il padre, pid figlio=%d�,pid);
else
printf(�Situazione di errore n�);
}and yes.. i have installed gcc and the build-essential package..
please help!!
thanks a lot
-
Re: Can’t compile simple C++ prog?
What are you using to write the file?
You should be using a text-editor like kate,vi,gedit etc. not a
program like OpenOffice.
-
Re: Can’t compile simple C++ prog?
i use vi for writing the program.. sometimes i also edit it with gedit..
never used openoffice.. u suggest to rewrite it again with gedit?
any help about how to fix this.. i really need to get it to work for the school exams
-
Re: Can’t compile simple C++ prog?
mstation,
It looks like whatever program you are using to write the program is adding weird characters, � should be «. It might have something to do with your locale or input method.