;
at the end of the #include
directives are the problem in your code. #include
directives don’t need (wrong to place indeed) semicolons at the end unlike C++
statements.
[Warning] extra tokens at end of #include directive [enabled by default]
It seems any character after >
in the directive causes this error/warning.
#include<iostream>a //error
Change to this:
#include <iostream>
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
class Problem3 {
public:
bool isPrime(long double num) {
srand(time(NULL));
return 0;
}
};
int main(){
cout<<"Hello Main";
}
EDIT:
Regarding the linker issue:
One suggestion is C++
expects types to be explicitly casted between types (more than C
). So, use a cast to convert time_t
which is returned by the time
to unsigned int
which is the input parameter type of srand
. (And of course this might not be the problem with linker error)
Instead of using stdlib.h
, try using <cstdlib>
, try if it helps. Because it uses namespace.
Apart from that, I have seen this snippet here. Use that pattern if it helps.
#include <cstdlib>
#include <iostream>
#include <ctime>
using namespace std;
int main()
{
srand(time(0)); //use current time as seed for random generator
int random_variable = rand();
cout << "Random value on [0 " << RAND_MAX << "]: "
<< random_variable << '\n';
}
there is already question in SO check if that helps Eclipse Method could not be resolved in a simple program C++
Never use time() to initialize srand()..
EDIT:
Now it seems many people got this kind of problem. I found a question How do I fix Eclipse CDT Error “Function ‘isdigit’ could not be resolved. He is facing the same problem. The asker suggested a work around to this in his question edit.
Quoted from that question:
I now believe this to be a Code Analysis problem. A better solution is
to edit the Code Analysis options to make «Function could not be
resolved» be a warning instead of an error. That way you can see the
warnings in Problems view, but continue to work. If the function is
REALLY missing, the compiler will tell you! I also have a new theory,
that the problem is with the Code Analyzer following symlinks, because
all of the «missing» functions are in symlinked include files. Would
love any input on this theory.
Hope that points to solve the problem.
Matroskin2 1 / 1 / 0 Регистрация: 20.01.2020 Сообщений: 7 |
||||
1 |
||||
24.02.2020, 22:12. Показов 6931. Ответов 7 Метки нет (Все метки)
Помогите. Компилятор выдает предупреждение :
0 |
Yetty 7428 / 5022 / 2891 Регистрация: 18.12.2017 Сообщений: 15,694 |
||||
24.02.2020, 22:17 |
2 |
|||
Matroskin2, пишите так:
1 |
1 / 1 / 0 Регистрация: 20.01.2020 Сообщений: 7 |
|
24.02.2020, 22:23 [ТС] |
3 |
С чем это связано? Я писал по методичке ну и в нете есть такие примеры как у меня .
0 |
hoggy 8737 / 4315 / 960 Регистрация: 15.11.2014 Сообщений: 9,762 |
||||
24.02.2020, 22:35 |
4 |
|||
srand((unsigned)time(0)); Код warning: use of old-style cast [-Wold-style-cast]
С чем это связано? методички пишут такие же балбесы, я пишут вот так:
1 |
2549 / 1208 / 358 Регистрация: 30.11.2013 Сообщений: 3,826 |
|
24.02.2020, 23:49 |
5 |
Добрый вечер, hoggy, а зачем перед Нету ли тут избыточности по типу
0 |
8737 / 4315 / 960 Регистрация: 15.11.2014 Сообщений: 9,762 |
|
25.02.2020, 00:00 |
6 |
а зачем перед std»::» ? оптимизация поиска имён. помогает тормозным и глупым
IDE чутка быстрее ориентироваться в коде.
1 |
Croessmah Неэпический 17848 / 10616 / 2049 Регистрация: 27.09.2012 Сообщений: 26,686 Записей в блоге: 1 |
||||
25.02.2020, 00:12 |
7 |
|||
rikimaru2013, а еще язык c++ прекрасен
1 |
4047 / 3301 / 923 Регистрация: 25.03.2012 Сообщений: 12,380 Записей в блоге: 1 |
|
25.02.2020, 01:13 |
8 |
С чем это связано? Я писал по методичке ну и в нете есть такие примеры как у меня . и что тебя смущает? warning это не ошибка
0 |
I can’t figure out why I am getting this error. I have tried #include several things and I have tried changing the location of srand.
#include <iostream.h>
#include <ctime>
class Horse {
int position;
public:
Horse(); //Horse constructor??? Per UML
int random;
srand( time(0));
void advance(){
random = rand() % 2;
cout << random;
}//end advance function
int getPosition(int y){
return y;
}//end getPosition function
};//end Horse class
Edited
by Nick Evan because:
Fixed formatting
Recommended Answers
I haven’t dealt with classes yet, but i would assume you’d have to place it inside the function. Have you tried ?
Jump to Post
All 3 Replies
Crutoy
0
Junior Poster in Training
I haven’t dealt with classes yet, but i would assume you’d have to place it inside the function. Have you tried ?
Ancient Dragon
5,243
Achieved Level 70
Team Colleague
Featured Poster
you can not put function calls in class declaration unless they are inside inline code. Move that srand() line to main()
int main()
{
srand(time(0));
}
Depending on the compiler you are using you may have to typecase time() to unsigned int instead of time_t.
sfuo
111
Practically a Master Poster
A class is made up of functions and variables so you can not randomly throw in a function call like srand() unless it is within one of it’s own functions. I would call srand() at the top of your main() function.
#include <iostream> //use iostream not iostream.h (.h is the c version)
#include <ctime>
using namespace std;
class Horse
{
int position;
int random;
public:
Horse(){}; //note the two curly brackets (this is the default constructor that is made if you do not include a constructor)
void advance()
{
random = rand() % 2;
cout << random;
}
int getPosition( int y )
{
return y;
}
};
int main()
{
srand(time(0));//seed your random here.
Horse test;
test.advance();
return 0;
}
Reply to this topic
Be a part of the DaniWeb community
We’re a friendly, industry-focused community of developers, IT pros, digital marketers,
and technology enthusiasts meeting, networking, learning, and sharing knowledge.
Я пытался отладить эту проблему некоторое время и, честно говоря, я просто не вижу, что я делаю неправильно.
Почему есть синтаксическая ошибка?
#include <iostream>;
#include <time.h>;
#include <stdio.h>;
#include <stdlib.h>;
using namespace std;class Problem3 {
public:
bool isPrime(long double num) {
srand(time(NULL));
return 0;
}
};
Я получаю ошибку,
«Функция« srand »не может быть решена».
- Теперь я хорошо понимаю, что мне не нужны точки с запятой после операторов включения
- Я использую Eclipse CDT вместе с MinGW в качестве моего компилятора
Как я решил проблему:
Это было связано с компилятором MinGW, который я использовал. Переход на Visual Studio решил проблему.
-3
Решение
;
в конце #include
Директивы являются проблемой в вашем коде. #include
Директивы не нуждаются (неправильно ставить) точки с запятой в конце, в отличие C++
заявления.
[Warning] extra tokens at end of #include directive [enabled by default]
Кажется, любой персонаж после >
в директиве вызывает эту ошибку / предупреждение.
#include<iostream>a //error
Изменить на это:
#include <iostream>
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
using namespace std;class Problem3 {
public:
bool isPrime(long double num) {
srand(time(NULL));
return 0;
}
};
int main(){
cout<<"Hello Main";
}
РЕДАКТИРОВАТЬ:
Что касается вопроса компоновщика:
Одно предложение C++
ожидает, что типы будут явно приведены между типами (более C
). Итак, используйте приведение для преобразования time_t
который возвращается time
в unsigned int
который является типом входного параметра srand
, (И, конечно, это может не быть проблемой с ошибкой компоновщика)
Вместо того, чтобы использовать stdlib.h
попробуйте использовать <cstdlib>
попробуйте, если это поможет. Потому что он использует пространство имен.
Кроме того, я видел этот фрагмент Вот. Используйте этот шаблон, если это поможет.
#include <cstdlib>
#include <iostream>
#include <ctime>
using namespace std;
int main()
{
srand(time(0)); //use current time as seed for random generator
int random_variable = rand();
cout << "Random value on [0 " << RAND_MAX << "]: "<< random_variable << '\n';
}
в SO уже есть вопрос, поможет ли это Метод Eclipse не может быть решен в простой программе C ++
Никогда не используйте time () для инициализации srand ()..
РЕДАКТИРОВАТЬ:
Теперь, похоже, у многих людей возникла такая проблема. Я нашел вопрос Как исправить ошибку Eclipse CDT «Функция« isdigit »не может быть решена». Он сталкивается с той же проблемой. Аскер предложил обойти это в своем вопросе редактирования.
Цитируется из этого вопроса:
Теперь я считаю, что это проблема анализа кода. Лучшее решение
отредактировать параметры анализа кода, чтобы сделать «Функция не может быть
решено «быть предупреждением, а не ошибкой. Таким образом, вы можете увидеть
предупреждения в представлении «Проблемы», но продолжают работать. Если функция
ДЕЙСТВИТЕЛЬНО отсутствует, компилятор скажет вам! У меня также есть новая теория,
что проблема с анализатором кода, следующим по символическим ссылкам, потому что
все «отсутствующие» функции находятся в символических включаемых файлах. Было бы
люблю любой вклад в эту теорию.
Надеюсь, что это указывает на решение проблемы.
4
Другие решения
;
не должно быть там после #include
,
3
#include <iostream>
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include
файлы не должны заканчиваться ;
2
«неявное преобразование теряет целую точность: ‘time_t’ (aka ‘long’) до ‘unsigned int’
Вы теряете точность неявно, потому что time()
возвращает long
, который больше, чем unsigned int
для вашей цели. Чтобы обойти эту проблему, вы должны явно указать результат (таким образом удалив «неявную потерю точности» ):
srand( static_cast<unsigned int>(time(NULL)));
Учитывая, что сейчас 2017, я редактирую этот вопрос, предлагая рассмотреть функции, предоставленные std::chrono::*
, определенные в <chrono>
, как часть С++ 11. Ваш любимый компилятор предоставляет С++ 11? Если нет, это действительно должно быть!
Чтобы получить текущее время, вы должны использовать:
#include <chrono>
void f() {
const std::chrono::time_point current_time = std::chrono::system_clock::now();
}
Зачем мне это беспокоиться, когда time()
работает?
IMO, достаточно одной причины: ясных, явных типов. Когда вы имеете дело с большими программами среди достаточно больших команд, зная, проходят ли значения, представляющие временные интервалы или «абсолютные» времена, и какие величины являются критическими. С помощью std::chrono
вы можете проектировать интерфейсы и структуры данных, которые переносимы и пропускать сингл «time-out-a-deadline-or-milliseconds-from-now-or-wait-was-it-seconds».