程序的输入一般有:标准的输入设备、磁盘文件或默认的变量初始值,通常前两种是必须的,程序的功能就是用来处理输入的内容。标准IO库提供类一些操作,例如 stringstream,使用这些操作可以是程序的处理简洁方便,下面是《C++ Primer》中的一个例子:
1 string line, word; // will hold a line and word from input, respectively 2 while (getline(cin, line)) { // read a line from the input into line 3 // do per-line processing 4 istringstream stream(line); // bind to stream to the line we read 5 while (stream >> word){ // read a word from line 6 // do per-word processing 7 } 8 } 9
如果是用来处理文件,第二行可以稍作更改,也可参考《C++ Primer》10.3.9节的最后一个例题
备注:“stringstream 类处理内存中字符串的 IO。”