код отлично работает в clion, 10 ошибок сгенерированы в терминале - PullRequest
0 голосов
/ 07 августа 2020
• 1000 по умолчанию создается в clion IDE. Все функции тестируются отдельно под main(), и все они работают отлично. Однако, когда я пытаюсь скопировать и вставить код в отдельный файл, который, скажем, я называю examples.cpp, насколько мне известно, я запускаю его отдельно в терминале (ma c os):
make examples
./examples

, и он должен создать исполняемый файл и запустить или, по крайней мере, это то, что я ожидаю. Вот как main.cpp, который я переименовал в отдельный файл вне папки проекта clion с именем examples.cpp, выглядит так:

#include <iostream>
#include <vector>
#include <ctime>
#include <cstring>
using std::cout;
using std::cin;
using std::endl;
using std::string;
using std::vector;


int no_val(){
    int age = 5;
    cout << age << endl;
    return 0;
}


double calculate_area(double width, double length){
    return width * length;
}


double calculate_area_inputs(){
    double width;
    double length;
    cout << "Enter room width: ";
    cin >> width;
    cout << "\nEnter room length: ";
    cin >> length;
    return width * length;
}


void signed_unsigned(){
    int x1 = -23;
    unsigned x2 = -55;
    cout << x1 << " " << x2 << endl;
}


long double types(){
    short int x1 = 10000;
    long double x2 = 1'000'000;
    long double x3 = 5e300;
    short product = 5 * 5;
    return product;
}


void sizes(){
    cout << "char: " << sizeof(char) << endl;
    cout << "string: " << sizeof(string) << endl;
    cout << "int: " << sizeof(int) << endl;
    cout << "float: " << sizeof(float) << endl;
    cout << "double: " << sizeof(double) << endl;
    cout << "short int: " << sizeof(short int) << endl;
    cout << "long int: " << sizeof(long int) << endl;
    cout << "long double: " << sizeof(long double) << endl;
    cout << "const int: " << sizeof(const int) << endl;

}

void other_syntax(){
    int x1 = 12U;
    int x2 = 15L;
    int x3 = 155UL;
    const int x4 = 1555LL;
}

void containers(){
    int abc [5];
    int xyz [5] {1, 2, 3, 4, 5};
    vector<int> aaa;
    vector<vector<int>> bbb {{1, 2, 3}, {4, 5, 6, 7}, {8, 9, 10}};
}

void statements(){
    int a = 6;
    int b = 5;
    if (a > b) cout << "a > b";
};

void control(int z){
    if (z > 10){
        cout << z;
        cout << "\n" << z * 10;
    }
    else {
        cout << "XYZ" << endl;
    }
}

void more_control(){
    enum Color{
        red, green, blue
    };
    Color screen_color {red};
    switch (screen_color) {
        case red: cout << "red"; break;
        case green: cout << "green"; break;
        case blue: cout << "blue"; break;
        default: "shouldn't execute";
    }
}

void more_control_2(){
    char expected_grade;
    cout << "What grade do you expect? ";
    cin >> expected_grade;
    switch (expected_grade) {
        case 'a': cout << "90 - 100";
            break;
        case 'b': cout << "80 - 90";
            break;
        case 'c': cout << "70 - 80";
            break;
        case 'd': cout << "60 - 60";
            break;
        default: cout << "Fail";
    }
}

int conditions(int n){
    return (n > 5) ? 23 : 55;
}

void initialize_vector(long int n){
    time_t t1, t2;
    time(&t1);
    vector<int> nums(n);
    time(&t2);
    double duration = difftime(t2, t1);
    printf ("time taken for function() %.2lf seconds.\n", duration);
}

void initialize_array(long int n){
    int nums [n];
    cout << "array: " << sizeof(nums) / sizeof(nums[0]) << endl;
}

void loops() {
    for (int i = 0, j = 100; i <= 100, j >= 0; ++i, --j)
        cout << "(" << i << ", " << j << ") ";
    cout << endl;
    int scores [] {30, 22, 40, 29, 5};
    for (auto score: scores)
        cout << score << " ";
    cout << endl;
    int i = 0;
    while (i <= 10){
        cout << i << " ";
        ++i;
    }
    cout << endl;
    do {
        cout << i << " ";
        ++i;
    } while(i <= 20);
}

void strings(){
    char xyz [] {"xyz"};
    char xyz2 [] {"akj"};
    xyz2[3] = 'p';
    for (auto i: xyz2)
        cout << i;
    cout << endl;
    char xyx [8];
    strcpy(xyx, "jansasf");
    for (auto i: xyx)
        cout << i;
    cout << endl;
    char xyx2 [20];
    strcpy(xyx2, "klm");
    strcpy(xyx2, "zef");
    strcat(xyx2, "jefomok");
    for (auto i: xyx2)
        cout << i;
}

void more_strings(){
    char s1 [10];
    for (auto i: s1)
        cout << i;
    char aaa [] = {"kkklllmmm"};
    cout << aaa << endl;
    cout << "aaa is of length: " << strlen(aaa) << endl;
    string s2;
    string s3 {"abcd"};
    string s4 {"abcde", 2};
    string s5 {3, 'X'};
    cout << s2 << endl;
    cout << s3 << endl;
    cout << s4 << endl;
    cout << s5 << endl;
}

void more_strings2(){
    string pt1 {"xyx"};
    string pt2 {" kkk"};
    string sentence = pt1 + pt2;
    cout << sentence << endl;
    for (auto i: sentence)
        cout << i << " ";
    cout << endl;
    cout << sentence.substr(4, 8) << endl;
    cout << sentence.size() << endl;
    cout << "Enter name: ";
    string pt3;
    getline(cin, pt3);
    cout << pt3 << endl;
    cout << "Enter name again: ";
    string pt4;
    getline(cin, pt4, 'a');
    cout << pt4 << endl;
}

void mathematics(){
    cout << "RAND_MAX on my system is: " << RAND_MAX << endl;
}

void xxx(int abc = 5){
    cout << abc;
}

long double factorial(int n){
    if (n == 1 || n == 0) {
        return 1;
    }
    return n * factorial(n - 1);

}

int add_numbers(int n1, int n2){
    return n1 + n2;
}

double add_numbers(double n1, double n2){
    return n1 + n2;
}

void print_array(const int xxx [], size_t size) {
    cout << '[';
    for (size_t i = 0; i <= size; ++i)
        cout << xxx[i] << ((i < size) ? " " : "");
    cout << ']';
}

void swap_values(int &a, int &b){
    int temp = a;
    a = b; b = temp;
}

void static_example()
{
    // static variable
    static int count = 0;
    cout << count << " ";

    // value is updated and
    // will be carried to next
    // function calls
    count++;
}

inline int add_nums(int a, int b){
    return a + b;
}


int main() {
    cout << add_nums(1, 5);
    return 0;
}

void forward_declaration(int n){
    cout << "OK: " << n;
}

Возникают следующие ошибки и предупреждения:

c++     examples.cpp   -o examples
examples.cpp:44:23: error: expected ';' at end of declaration
    long double x2 = 1'000'000;
                      ^
                      ;
examples.cpp:73:16: error: expected ';' at end of declaration
    int xyz [5] {1, 2, 3, 4, 5};
               ^
               ;
examples.cpp:75:22: error: a space is required between consecutive right angle
      brackets (use '> >')
    vector<vector<int>> bbb {{1, 2, 3}, {4, 5, 6, 7}, {8, 9, 10}};
                     ^~
                     > >
examples.cpp:75:28: error: expected ';' at end of declaration
    vector<vector<int>> bbb {{1, 2, 3}, {4, 5, 6, 7}, {8, 9, 10}};
                           ^
                           ;
examples.cpp:98:23: error: expected ';' at end of declaration
    Color screen_color {red};
                      ^
                      ;
examples.cpp:103:18: warning: expression result unused [-Wunused-value]
        default: "shouldn't execute";
                 ^~~~~~~~~~~~~~~~~~~
examples.cpp:143:32: warning: relational comparison result unused
      [-Wunused-comparison]
    for (int i = 0, j = 100; i <= 100, j >= 0; ++i, --j)
                             ~~^~~~~~
examples.cpp:146:9: error: definition of variable with array type needs an
      explicit size or an initializer
    int scores [] {30, 22, 40, 29, 5};
        ^
examples.cpp:146:18: error: expected ';' at end of declaration
    int scores [] {30, 22, 40, 29, 5};
                 ^
                 ;
examples.cpp:147:10: warning: 'auto' type specifier is a C++11 extension
      [-Wc++11-extensions]
    for (auto score: scores)
         ^
examples.cpp:147:20: warning: range-based for loop is a C++11 extension
      [-Wc++11-extensions]
    for (auto score: scores)
                   ^
examples.cpp:163:10: error: definition of variable with array type needs an
      explicit size or an initializer
    char xyz [] {"xyz"};
         ^
examples.cpp:163:16: error: expected ';' at end of declaration
    char xyz [] {"xyz"};
               ^
               ;
examples.cpp:164:10: error: definition of variable with array type needs an
      explicit size or an initializer
    char xyz2 [] {"akj"};
         ^
examples.cpp:164:17: error: expected ';' at end of declaration
    char xyz2 [] {"akj"};
                ^
                ;
examples.cpp:166:10: warning: 'auto' type specifier is a C++11 extension
      [-Wc++11-extensions]
    for (auto i: xyz2)
         ^
examples.cpp:166:16: warning: range-based for loop is a C++11 extension
      [-Wc++11-extensions]
    for (auto i: xyz2)
               ^
examples.cpp:171:10: warning: 'auto' type specifier is a C++11 extension
      [-Wc++11-extensions]
    for (auto i: xyx)
         ^
examples.cpp:171:16: warning: range-based for loop is a C++11 extension
      [-Wc++11-extensions]
    for (auto i: xyx)
               ^
examples.cpp:178:10: warning: 'auto' type specifier is a C++11 extension
      [-Wc++11-extensions]
    for (auto i: xyx2)
         ^
examples.cpp:178:16: warning: range-based for loop is a C++11 extension
      [-Wc++11-extensions]
    for (auto i: xyx2)
               ^
examples.cpp:184:10: warning: 'auto' type specifier is a C++11 extension
      [-Wc++11-extensions]
    for (auto i: s1)
         ^
examples.cpp:184:16: warning: range-based for loop is a C++11 extension
      [-Wc++11-extensions]
    for (auto i: s1)
               ^
examples.cpp:190:14: error: expected ';' at end of declaration
    string s3 {"abcd"};
             ^
             ;
examples.cpp:191:14: error: expected ';' at end of declaration
    string s4 {"abcde", 2};
             ^
             ;
examples.cpp:192:14: error: expected ';' at end of declaration
    string s5 {3, 'X'};
             ^
             ;
examples.cpp:200:15: error: expected ';' at end of declaration
    string pt1 {"xyx"};
              ^
              ;
examples.cpp:201:15: error: expected ';' at end of declaration
    string pt2 {" kkk"};
              ^
              ;
examples.cpp:204:10: warning: 'auto' type specifier is a C++11 extension
      [-Wc++11-extensions]
    for (auto i: sentence)
         ^
examples.cpp:204:16: warning: range-based for loop is a C++11 extension
      [-Wc++11-extensions]
    for (auto i: sentence)
               ^
14 warnings and 16 errors generated.
make: *** [examples] Error 1

Итак, я попробовал (и я не уверен, действительно ли это вообще):

c++ examples.cpp -std=c++11

У меня было меньше ошибок, но все равно не удалось:

examples.cpp:44:23: error: expected ';' at end of declaration
    long double x2 = 1'000'000;
                      ^
                      ;
examples.cpp:103:18: warning: expression result unused [-Wunused-value]
        default: "shouldn't execute";
                 ^~~~~~~~~~~~~~~~~~~
examples.cpp:143:32: warning: relational comparison result unused
      [-Wunused-comparison]
    for (int i = 0, j = 100; i <= 100, j >= 0; ++i, --j)
                             ~~^~~~~~
2 warnings and 1 error generated.

и вот что я получаю, когда использую std = c ++ 20:

error: invalid value 'c++20' in '-std=c++20'
note: use 'c++98' or 'c++03' for 'ISO C++ 1998 with amendments' standard
note: use 'gnu++98' or 'gnu++03' for 'ISO C++ 1998 with amendments and GNU
      extensions' standard
note: use 'c++11' for 'ISO C++ 2011 with amendments' standard
note: use 'gnu++11' for 'ISO C++ 2011 with amendments and GNU extensions'
      standard
note: use 'c++14' for 'ISO C++ 2014 with amendments' standard
note: use 'gnu++14' for 'ISO C++ 2014 with amendments and GNU extensions'
      standard
note: use 'c++17' for 'ISO C++ 2017 with amendments' standard
note: use 'gnu++17' for 'ISO C++ 2017 with amendments and GNU extensions'
      standard
note: use 'c++2a' for 'Working draft for ISO C++ 2020' standard
note: use 'gnu++2a' for 'Working draft for ISO C++ 2020 with GNU extensions'
      standard

Как правильно запускать файлы c ++ в терминале и в целом? почему он не работает в терминале, а тот же код отлично работает в IDE? Прошу прощения, если это звучит глупо, и заранее спасибо.

1 Ответ

1 голос
/ 07 августа 2020

Я не знаю, что вы пытаетесь сделать со своим кодом, но вам нужно скомпилировать с C ++ 17:

g++ -std=c++17 examples.cpp -o examples
./examples

Я получаю 2 других предупреждения

Здесь одно предупреждение:

        default: "shouldn't execute";

Вероятно, вы имели в виду:

default:
   cout << "shouldn't execute";
   break;

Второе предупреждение здесь:

for (int i = 0, j = 100; i <= 100, j >= 0; ++i, --j)

i <= 100 is осталось неиспользованным, и только j >= 0 будет учитываться из-за оператора запятой. Вам нужно написать:

i <= 100 && j >= 0
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...