C ++ single-line string summation (Code tutorial), summation
C ++ single-line string summation (Code tutorial)
# Include <iostream> # include <string> # include <sstream> using namespace std; int main () {string line; while (getline (cin, line )) {// write the entire row of data (together with spaces) into line. If you enter string in the cin> mode, int sum = 0, x; stringstream ss (line) is stopped ); // create a sequence stream string ss while (ss> x) {// read ss to x sum + = x ;}cout <sum <endl ;} return 0 ;}
Getline () is defined in the <string> header file. The function is to take a line string, read the line break \ n, and discard the line break. If you need to read the character, read the next line.
Getline (cin, str); the first parameter is the input stream object, and the second parameter is the string object.
Stringstream, derived from iostream, provides the string read/write function.