C++ Tutorial/File Stream/istrstream

Материал из C\C++ эксперт
Перейти к: навигация, поиск

Attempt to read from empty stream

<source lang="cpp">#include <iostream> using std::cout; using std::endl;

  1. include <string>

using std::string;

  1. include <sstream>

using std::istringstream; int main() {

  string input( "" );
  istringstream inputString( input );
  // attempt to read from empty stream
  long value;
  inputString >> value;
  if ( inputString.good() )
     cout << "\n\nlong value is: " << value << endl;
  else
     cout << "\n\ninputString is empty" << endl;
  return 0;

}</source>

inputString is empty

Demonstrating input from an istringstream object

<source lang="cpp">#include <iostream> using std::cout; using std::endl;

  1. include <string>

using std::string;

  1. include <sstream>

using std::istringstream; int main() {

  string input( "Input test 123 4.7 A" );
  istringstream inputString( input );
  string string1;
  string string2;
  int integer;
  double double1;
  char character;
  inputString >> string1 >> string2 >> integer >> double1 >> character;
  cout << "\nstring1: " << string1
     << "\nstring2: " << string2 << "\n   int: " << integer
     << "\ndouble: " << double1 << "\n  char: " << character;
  return 0;

}</source>

string1: Input
string2: test
   int: 123
double: 4.7
  char: A"

How to read the contents of any array that contains text

<source lang="cpp">#include <iostream>

  1. include <strstream>

using namespace std; int main() {

 char s[] = "1.3 this is a test <<>><<?!\n";
 istrstream ins(s);
 char ch;
 ins.unsetf(ios::skipws); // don"t skip spaces
 while (ins) { // false when end of array is reached
   ins >> ch;
   cout << ch;
 }
 return 0;

}</source>

1.3 this is a test <<>><<?!

Read and display binary data

<source lang="cpp">#include <iostream>

  1. include <strstream>

using namespace std; int main() {

 char *p = "this is a test\1\2\3\4\5\6\7";
 istrstream ins(p);
 char ch;
 
 while (!ins.eof()) {
   ins.get(ch);
   cout << hex << (int) ch << " ";

}
 return 0;

}</source>

74 68 69 73 20 69 73 20 61 20 74 65 73 74 1 2 3 4 5 6 7 7 "

Use istrstream to read int, float and char

<source lang="cpp">#include <iostream>

  1. include <strstream>

using namespace std; int main() {

 char s[] = "10 Hello 0x75 42.73 OK";
 istrstream ins(s);
 int i;
 char str[80];
 float f;
 // reading: 10 Hello
 ins >> i;
 ins >> str;
 cout << i << " " << str << endl;
 // reading 0x75 42.73 OK
 ins >> hex >> i;
 ins >> f;
 ins >> str;
 cout << hex << i << " " << f << " " << str;
 return 0;

}</source>

10 Hello
75 42.73 OK"