• c++ 读取标准输入中的一行,然后从行首提取数字、字符串


    
    

    #include<iostream>
    using namespace std;
    #include<string>
    #include<sstream>

    
    

    int main(){

    int Np, Nn;

    
    

    cout<<"input a line: "<<endl;
    string line; getline(cin, line);

    
    

    stringstream strm( line );

    
    

    strm>>Np; strm>>Nn; cout<<"Np = "<<Np<<" Nn = "<<Nn<<endl;

    return 0;
    }

    ~         

    运行结果:

    luyi@Swagger:~/test/getline$ g++ getline.cpp; ./a.out 
    input a line: 
    3 5 7 sadfa zxcv
    Np = 3     Nn = 5

    可以看到,输入了" 3 5 7 sadfa zxcv"一整行,然后把行首第一个非空格的数字赋给了Np, 第二个赋给了Nn。

    也可以提取行首字符串,也是从第一个非零的字符开始:#include<iostream>using namespace std;

    #include<string>
    #include<sstream>
    
    int main(){
            
            int Np, Nn;
    
            cout<<"input a line: "<<endl;
            string line; getline(cin, line);
    
            stringstream strm( line );
    
            string name;
    
            strm>>name; cout<<"name ="<<name<<endl;
            strm>>Np; strm>>Nn; cout<<"Np = "<<Np<<"	 Nn = "<<Nn<<endl; 
    return 0; } ~

    运行结果:

    luyi@Swagger:~/test/getline$ g++ getline.cpp ; ./a.out
    input a line: 
      Jerry 3 5 2342
    name =Jerry
    Np = 3     Nn = 5

     也可以再次给 strm 内容赋值,使用 strm.str( string ),但是 strm 第二次使用的时候,一定要先clear,否则可能会出错(亲测)。  

    以下是正确代码

    #include<iostream>
    using namespace std;
    #include<string>
    #include<sstream>
    
    int main(){
    
            int Np, Nn;
    
            cout<<"input a line: "<<endl;
            string line; getline(cin, line);
    
            stringstream strm( line );
    
            string name;
    
            strm>>name; cout<<"name ="<<name<<endl;
            strm>>Np; strm>>Nn; cout<<"Np = "<<Np<<"	 Nn = "<<Nn<<endl;
    
            string newname; cout<<"input a new name: ";
            getline(cin, line); strm.clear(); strm.str(line); strm>>newname; cout<<"new name="<<newname<<endl;
    
            return 0;
    }
    ~        

    如果不写中间的 strm.clear(); 有时不出错,有时出错,所以是不可靠的。

  • 相关阅读:
    Android虚拟、实体键盘不能同时使用?
    libwebsockets 运行问题
    Qt TabWidget QTabBar 宽高设置
    I.MX6 recovery mode hacking
    libwebsockets libwebsockets-webserver.c hacking
    MySQL(六)常用语法和数据类型
    MySQL(五)汇总和分组数据
    MySQL(四)字段及常用函数
    MySQL(三)用正则表达式搜索
    MySQL(二)数据的检索和过滤
  • 原文地址:https://www.cnblogs.com/luyi07/p/14510203.html
Copyright © 2020-2023  润新知