Академический Документы
Профессиональный Документы
Культура Документы
* File: 20160913_CPP_L04.cpp.
* Title: 2016-09-13 C++ Lesson 04
* Author: Renato Montes
* Description: Notes for Albert Wei's C++ class
*/
#include <iostream>
using namespace std;
int main() {
int m = 11, n = 12;
cin >> m >> n;
cout << m << ' ' << n << endl;
}
//when entering hello, it fails
//but n retains the previous value
//be careful: variable is set to zero only when the string is in a good state
//some methods:
length(), size() //both return the length
//Albert always uses size()
//it turns out that a string is a container (a container of chars) & all
//containers have a size() method
//vector is another container
//e.g.:
string word;
cin >> word; //try to read a word
while(cin >> word)
//process word
//second version:
for (auto& c : s)
//process c
void uppercase(string& s) {
for(auto& c : s)
c = toupper(c);
}
/* Reading a line */
//getline takes three arguments:
getline(stream, str, delim)
//a stream (here istream), a string, and a delimiter (a char)
// (defaults to '\n', can write with
// just two arguments)
//keeps extrating characters from stream & storing them in _str_ until:
//1) end-of-file becomes true (sets eofbit)
//2) a char equal to delim has been extracted (this character is discarded)
//3) a failure case: str.max_size() characters have been stored (sets failbit)
//If no characters have been extracted, sets failbit as well.
//getline returns _stream_
//remember a stream can be used as true or false, and thus can put it in a
// while loop
//Example:
/* Summing integers obtained interactively */
string line;
int n, sum = 0;
while (1) {
cout << "Enter an integer: ";
if (!getline(cin, line)) {
cin.clear();
break;
}
istringstream iss(line);
if (iss >> n)
sum += n;
}
cout << sum << endl;