If there is a file aaa.txt, there are several lines, do not know that each line contains several integers, to program the output of the sum of each line of integers, how to implement?
Since cin>> cannot discern the difference between a space and a carriage return, it is only possible to read the data into a string variable in a getline way, but it is a little laborious to separate several integers in a string variable. A good way to do this is with a string stream:
1#include <iostream>2#include <sstream>3#include <fstream>4 using namespacestd;5 intMain ()6 {7Ifstreaminch("Aaa.txt");8 for(stringS Getlineinch, s);)9 {Ten intA, sum =0; One for(Istringstream sin (s); sin >> A; sum + =a); Acout << sum <<Endl; - } -Cin.Get(); the return 0; -}
To be reasonable, the procedure is somewhat presumptuous. Istringstream sin (s) was supposed to be a separate line, and the result is not only that the sum+=a are shrunk to the step portion of the loop structure description. As a result, the loop body is empty, and then the description part of the For loop is followed by a semicolon to make a separate statement, but it does complete the cumulative work. As a separate cycle, the last ";" Still cannot be forgotten!! Because the program is small, so the readability is not to the point of injury, please readers to see this style.
Istringstream is the input string stream, which is described in the Sstream header file. This statement is similar to a file flow operation, except that when a sin is created, its argument is a string object. It is to treat the entity of a string as an input stream, so that sin>>a is the input of an integer from a string stream into a, the loser loses, and loses to the last integer in the string!
String streams are useful, and sometimes you want to output the content to a string one by one, and then format the output based on the results of the calculation. This is how it works with a string stream.
C + + code:string stream (String stream)