`

零星笔记,待整理

    博客分类:
  • c++
阅读更多
  //用 getline 函数从输入读取整行内容。然后为了获得每行中的单词,将一个   
  //istringstream 对象与所读取的行绑定起来,这样只需要使用普通的
  //string 输入操作符即可读出每行中的单词。

  string line, word;// will hold a line and word from input, rectively
  while (getline(cin, line))   
  {            // read a line from the input into line
            // do per-line processing
    istringstream stream(line);  // bind to stream to the line we read
    while (stream >> word)
    {          // read a word from line
           // do per-word processing
    }
  }


//stringstream 对象的一个常见用法是,需要在多种数据类型之间实现自动格式化时
//使用该类类型
     int val1 = 512, val2 = 1024;
    ostringstream format_message;
    // ok: converts values to a string representation
    format_message << "val1: " << val1 << "\n"
                   << "val2: " << val2 << "\n";

//相反,用 istringstream 读 string 对象,即可重新将数值型数据找回来
   istringstream input_istring(format_message.str());
   string dump; // place to dump the labels from the formatted message
   input_istring >> dump >> val1 >> dump >> val2;
   cout << val1 << " " << val2 << endl;  // prints 512 1024

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics