istringstream"类和getline()的用法分

本文介绍如何利用C++中的getline函数读取一行输入,并通过istringstream对象按空格分隔来解析这一行数据。示例代码展示了如何区分注释行与数值行,以及如何将这些数值读入并打印。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

getline
Syntax:
  #include <string>
  istream& getline( istream& is, string& s, char delimiter = '\n' );
 
getline是读一行 遇到换行符才结束
istringstream对象可以绑定一行字符串,然后以空格为分隔符把该行分隔开来。
(以空格分隔提取字符)
 
举个例子 
来自cppprefence
 
 
 // expects either space-delimited numbers or lines that start with
  // two forward slashes (//)#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{    string s;
  while( getline(cin,s) )
 {
    if( s.size() >= 2 && s[0] == '/' && s[1] == '/' ) {
      cout << "  ignoring comment: " << s << endl;
    } else {
      istringstream ss(s);
      double d;
      while( ss >> d ) {
        cout << "  got a number: " << d << endl;
      }
    }
  }
 
When run with a user supplying input, the above code might produce this output:输入如下字符: // test
 回车      
ignoring comment: // test
  23.3 -1 3.14159
    got a number: 23.3
    got a number: -1
    got a number: 3.14159
  // next batch
    ignoring comment: // next batch
  1 2 3 4 5
    got a number: 1
    got a number: 2
    got a number: 3
    got a number: 4
    got a number: 5
  50
    got a number: 50

可以看到getline 读一行 istringstream 按空格分别读进s。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值