zoukankan      html  css  js  c++  java
  • 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(); 有时不出错,有时出错,所以是不可靠的。

  • 相关阅读:
    【开发技术】Eclipse设置软tab(用4个空格字符代替)及默认utf-8文件编码(unix)
    【开发技术】Xcode3与xcode4.2模板对比(Xcode4.2开发之一些变化)
    cobol
    头文件的相互包含会导致错误
    ndk eclipse集成
    为何要用到NDK?
    Android之NDK开发
    一个完整的NDK编译过程
    NDK中 .so文件的加载
    Android.mk 变量解释
  • 原文地址:https://www.cnblogs.com/luyi07/p/14510203.html
Copyright © 2011-2022 走看看