Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.1k views
in Technique[技术] by (71.8m points)

visual c++ - Only one variable is printing C++

//libraries
#include <iostream>

//standard namepace
using namespace std;


int Car() {
    int a;
    int b;
    
    cout << "Fuel Tank" << endl;
    cin >> a;
    cout << "MPG" << endl;
    cin >> b;

    return a, b;
}
int main() {
    int a;
    int b;
    
    a,b = Car();
    
    cout << "Print Values " << (a,b);    // <--- Line 25

    return 0;
}

Let's say you put 10 and 15 as the first and second input. Why is 15 the only variable to print in the cout statement on line 25.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

That's not how C++ works.

You need:

std:: pair<int, int>  Car() {
    ...
    return {a, b};
}
auto [a, b] = Car();
std::cout << a << ", " << b;

What you have:

int Car()

Car is a function which returns 1 int.

return a, b;

Here you have the comma operator which evaluates every argument and discards all but the last one. So it returns b.

a, b = Car();
(a, b)

Again the comma operator. a is discarded and b is assigned. Then a is discarded and b is printed.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...