C++ Tutorial/File Stream/istrstream — различия между версиями
Admin (обсуждение | вклад) м (1 версия: Импорт контента...) |
Admin (обсуждение | вклад) м (1 версия: Импорт контента...) |
(нет различий)
|
Текущая версия на 10:31, 25 мая 2010
Содержание
Attempt to read from empty stream
#include <iostream>
using std::cout;
using std::endl;
#include <string>
using std::string;
#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;
}
inputString is empty
Demonstrating input from an istringstream object
#include <iostream>
using std::cout;
using std::endl;
#include <string>
using std::string;
#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;
}
string1: Input string2: test int: 123 double: 4.7 char: A"
How to read the contents of any array that contains text
#include <iostream>
#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;
}
1.3 this is a test <<>><<?!
Read and display binary data
#include <iostream>
#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;
}
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
#include <iostream>
#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;
}
10 Hello 75 42.73 OK"