In the string transp, it was to appear all 4 names, however, only the last one appears

Asked

Viewed 28 times

-1

#include <iostream>

using namespace std;

void texto();
void soma(int n1, int n2);
int soma2(int n1, int n2);
void tr(string tra[4]);

int main(){
    int res;
    string transp[4]=("carro","moto","barco","aviao");

    soma(15,5);
    res=soma2(175,25);

    cout << "valor de res: " << res << "\n";

    tr(transp);

         return 0;
}

void texto(){
    cout << "canal fessor bruno\n";
}

void soma(int n1, int n2){
    cout << "soma dos valores: " << n1+n2 << "\n";
}

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

void tr(string tra[4]){
    for(int i=0; i<4; i++){
        cout << tra[i] << "\n";
    }
}

1 answer

3

The way you are initiating the array the problem is in using parentheses instead of keys.

For this case the correct boot is:

string transp[4]={"carro","moto","barco","aviao"};

You can see the code working here

By using parentheses instead of keys you are grouping expressions and using the comma (comma) operator. This operator is not very well known and it serves to separate two or more expressions (in your case a string is an expression) and the expressions are evaluated one by one from left to right and the value of the whole expression is the value of the last expression in the list (in your case the value of the expression is "airplane", so it puts in all positions.)

For more details you can check:

Built-in comma Operator

Wikipedia comma Operator

Browser other questions tagged

You are not signed in. Login or sign up in order to post.