C++primer 习题8.3疑问
{
int ival;
while(in>>ival,!in.eof()){
if(in.bad())
throw std::runtime_error("IO stream corrupted");
if(in.fail()){
std::cerr<<"bad data ,try again"<<std::endl;
in.clear();
in.ignore(200,' ')
;
continue;
}
//读入正常
std::cout<<ival<<" ";
}
in.clear();
return in;
}
#include <stdio.h>
char s[]="123 ab 4";
char *p;
int v,n,k;
void main() {
p=s;
while (1) {
k=sscanf(p,"%d%n",&v,&n);
printf("k,v,n=%d,%d,%d\n",k,v,n);
if (1==k) {
p+=n;
} else if (0==k) {
printf("skip char[%c]\n",p[0]);
p++;
} else {//EOF==k
break;
}
}
printf("End.\n");
}
//k,v,n=1,123,3
//k,v,n=0,123,3
//skip char[ ]
//k,v,n=0,123,3
//skip char[a]
//k,v,n=0,123,3
//skip char[b]
//k,v,n=1,4,2
//k,v,n=-1,4,2
//End.
/*
* 读取文件中的数字
*/
#include <string>
#include <iostream>
#include <fstream>
using namespace std;
int main(int argc,char**argv){
if(argc<2){
cerr<<"Invaild input"<<endl;
return -1;
}
ifstream fin(argv[1]);
if(!fin){
cerr<<"Invaild file:"<<argv[1]<<endl;
return -2;
}
string line;
string digits("0123456789");
while(getline(fin,line)){
cout<<"Read from file: "<<line<<endl;
cout<<">>>>:";
string word;
string::size_type pos=0,pos2=0;
while((pos2=line.find_first_of(digits,pos))!=string::npos){
pos=line.find_first_not_of(digits,pos2);
if(pos!=string::npos){
word=line.substr(pos2,pos-pos2);
}
else{
word=line.substr(pos2);
}
cout<<word<<' ';
}
cout<<endl;
}
return 0;
}