getline(istream &in, string &s)
从输入流读入一行到string s
•功能:
–从输入流中读入字符,存到string变量
–直到出现以下情况为止:
•读入了文件结束标志
•读到一个新行
•达到字符串的最大长度
–如果getline没有读入字符,将返回false,可用于判断文件是否结束
cin.getline(数组名, 数组大小)
从输入流读入一行到string s
•功能:
–从输入流中读入字符,存到string变量
–直到出现以下情况为止:
•读入了文件结束标志
•读到一个新行
•达到字符串的最大长度
–如果getline没有读入字符,将返回false,可用于判断文件是否结束
cin.getline(数组名, 数组大小)
// chapter5.7.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
const int nameSize = 40;
struct Car {
char producer[nameSize];
int prodYear;
};
void print(Car* car, int num) {
cout << "Here is your collection:" << endl;
for (int i = 0; i < num; i++) {
cout << car[i].prodYear << " " << car[i].producer << endl;
}
}
int _tmain(int argc, _TCHAR* argv[]) {
int carNum = 0;
cout << "How many cars do you wish to catalog?" << endl;
cin >> carNum;
cin.get();
Car* car = new Car[2];
for (int i = 0; i < carNum; i++) {
cout << "Please enter the make:" << endl;
cin.getline(car[i].producer, nameSize);
cout << "Please enter the year made:" << endl;
cin >> car[i].prodYear;
cin.get();
}
print(car, carNum);
return 0;
}
// chapter5.7.2.cpp : Defines the entry point for the console application.
// getline
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
struct Car {
string producer;
int prodYear;
};
void print(Car* car, int num) {
cout << "Here is your collection:" << endl;
for (int i = 0; i < num; i++) {
cout << car[i].prodYear << " " << car[i].producer << endl;
}
}
int _tmain(int argc, _TCHAR* argv[]) {
int carNum = 0;
cout << "How many cars do you wish to catalog?" << endl;
cin >> carNum;
cin.get();
Car* car = new Car[carNum];
for (int i = 0; i < carNum; i++) {
cout << "Please enter the make:" << endl;
getline(cin, car[i].producer);
cout << "Please enter the year made:" << endl;
cin >> car[i].prodYear;
cin.get();
}
print(car, carNum);
return 0;
}