天天看点

C++ 字符串的输入

每次读取一个单词用cin

读取一行字符串:

    (1)面向行的输入:getline() 通过换行符来确定行尾,但不保存换行符

            getline( )函数读取整行 回车键输入的换行符来确定结尾 调用方法:cin.getline(   ) 参数:第一个参数数组名称,第二个参数读取的字符数

#include<iostream>

int main() 

{

using namespace std;

const int ArSize = 20;

char name[ArSize];

char dessert[ArSize];

cout << "Enter your name:\n";

cin.getline(name, ArSize);

cout<<"Enter your favorite dessert:\n";

cin.getline(dessert, ArSize);

cout << "I have some delicious" << dessert;

cout << "for you" << name << ".\n";

return 0;

}

    (2)面向行的输入 get()并不在读取并丢弃换行符 而是将其留在输入队列中

        cin.get(name,ArSize)

cin.get(数组名,数组数量)。get()

#include<iostream>

int main() 

{

using namespace std;

const int ArSize = 20;

char name[ArSize];

char dessert[ArSize];

cout << "Enter your name:\n";

cin.get(name, ArSize).get();

cout << "Enter your dessert\n";

cin.get(dessert, ArSize).get();

cout << "I have some delicious " << dessert;

cout << "for you." << name << ".\n";

return 0;

}

为什么使用get() 而不是getline()呢 首先老式实现没有getline(),其次是get()可以知道是读取了整行,而不是由于数组已经填满

混合输入字符串和数字

//混合输入字符串和数字

#include<iostream>

int main() 

{

using namespace std;

cout << "What year was your house build?\n ";

int year;

cin >> year;

cin.get();

cout << "What is its street address?\n";

char address[80];

cin.getline(address, 80);

cout << "your build:" << year << endl;

cout << "your address:" << address << endl;

return 0;

}