1

私はゆっくりと自分で c++ を学ぼうとしていますが、関数の使用に行き詰まりました。最初の問題を乗り越える方法を見つけましたが、最初に意図したようにできなかった理由がわかりません。これが作業プログラムです。

// ex 6, ch 2
#include <iostream> 
using namespace std; 

void time(int, int);
int main() 
{
int h, m; 
cout << "Enter the number of hours: "; 
cin >> h; 
cout << endl; 
cout << "Enter the number of minutes: "; 
cin >> m; 
cout << endl; 
time(h, m); 

cin.get();
cin.get();
return 0; 
} 

void time(int hr, int mn)
{
 cout << "The time is " << hr << ":" << mn;  
}

そして、これが私がやりたい方法です。

// ex 6, ch 2
#include <iostream> 
using namespace std; 

void time(int, int);
int main() 
{
int h, m; 
cout << "Enter the number of hours: "; 
cin >> h; 
cout << endl; 
cout << "Enter the number of minutes: "; 
cin >> m; 
cout << endl; 
cout << "The time is " << time(h, m); 

cin.get();
cin.get();
return 0; 
} 

void time(int hr, int mn)
{
 cout << hr << ":" << mn;  
}

私の頭では、どちらも同じものを返しますが、コンパイラはそうではないと考えています(理由を知りたいです)。

編集:奇妙な理由でこのように機能するようです。

cout << "The time is "; 
time(h, m); 

それ以上ではないにしても、それは私をより混乱させました。

4

2 に答える 2

3
cout << "The time is " << time(h, m); 

timeは何も返しませんが、この場合に何かを送信するには、関数を直接呼び出すcoutのではなく、値 (この場合はおそらく文字列) を返す必要があります。timecout

于 2013-06-08T13:05:46.400 に答える
1

timeを返すように -functionを編集する必要がありますstringstringstreamint を string に変換するために使用しています。

#include <sstream>
...
string time(int, int);

...

string time(int hr, int mn)
{
    stringstream sstm;
    sstm << hr << ":" << mn;
    string result = sstm.str();
    return result;
}

これで、次のように直接使用できます。

cout << "The time is " << time(h, m); 
于 2013-06-08T13:08:34.290 に答える