C++之与控制台交互

一 cin的基本使用

1 代码

#include
using namespace std;

int main ()
{
int i;

cout << "Please enter an integer value: ";
cin >> i;
cout << "The value you entered is " << i;
cout << " and its double is " << i*2 << ".\n";

return 0;

}
2 运行

[root@localhost test]# g++ test.cpp -o test
[root@localhost test]# ./test
Please enter an integer value: 3
The value you entered is 3 and its double is 6.
3 说明

cin>>a>>b;
以上情况,用户必须输入两个数据,一个给变量a,一个给变量b。输入时,两个变量之间可以以任何有效的空白符合间隔,包括空格、跳跃符或换行符。

二 读取字符串

1 代码

#include
#include
using namespace std;

int main ()
{
string mystr;
cout << "What’s your name? ";
getline (cin, mystr);
cout << "Hello " << mystr << “.\n”;
cout << "What is your favorite color? ";
getline (cin, mystr);
cout << “I like " << mystr << " too!\n”;
return 0;
}
2 运行

[root@localhost test]# g++ test.cpp -o test
[root@localhost test]# ./test
What’s your name? cakin jim
Hello cakin jim.
What is your favorite color? red
I like red too!
3 说明

两次调用getline函数都使用同一字符串变量mystr。在第二次调用的时候,程序会自动用第二次输入的内容取代以前的内容。

三 字符串流的使用

1 代码

#include
#include
#include
using namespace std;

int main ()
{
string mystr;
float price=0;
int quantity=0;

cout << "Enter price: ";
getline (cin,mystr);
stringstream(mystr) >> price;
cout << "Enter quantity: ";
getline (cin,mystr);
stringstream(mystr) >> quantity;
cout << "Total price: " << price*quantity << endl;
return 0;
}
2 运行

[root@localhost test]# g++ test.cpp -o test
[root@localhost test]# ./test
Enter price: 5
Enter quantity: 6
Total price: 30
3 说明

我们要求用户输入数据,但不同于从标准输入中直接读取数值,我们使用函数getline从标准输入流中读取字符串对象mystr,再从这个字符串对象中提取数值price和quantity。

我们可以像使用流一样使用stringstream的对象,可以像使用cin那样使用操作符,>>后跟一个整数变量来提取整数数据。

猜你喜欢

转载自blog.csdn.net/liuxingjiaoyuC/article/details/104714881