Reading files

Hi

Can you use the cin function on a string variable?

I am trying to read input from a file line by line. I want to be able to output the correct lines to a file and the incorrect to a file.

Each line holds three pieces of information separated by a space and then finally a newline.

So i want to read the input line by line using getline. Then want to take each piece of information for validation?

Can i do this by using cin on the value returned by the getline or must i read it char by char?

You could use getline to read the whole line into a string. Then use a stringstream to easily read the three parts of that string.
1
2
3
4
5
6
7
    string line = "one 123 two";
    int b;
    string a, c;
    istringstream ss(line);
    ss >> a >> b >> c;
	
    cout << "a: " << a << " b: " << b << " c: " << c << endl;

Output:
a: one b: 123 c: two
Last edited on
OK i' trying to get my head around stringstream and how you would test for errors.

what on earth is going on here:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <string>       // std::string
#include <iostream>     // std::cout
#include <sstream>      // std::stringstream

using namespace std;

int main () {

  stringstream ss;

  ss << 100 << 'f'<< "hello" << 200;

  int foo,bar;

  string s;
  ss >> foo >> s >> bar;

  cout << "foo: " << foo << '\n';
  cout << "s:" << s << endl;
  cout << "bar: " << bar << '\n';

  return 0;
}


the output is:

foo: 100
s:fhello200
bar: 134515753

cos theres no white space between f and hello.

Fair enough.

Why then does it stop when it encounters the char f but does not stop when it encounters the int 200?
Last edited on
When you do this, the process first skips any whitespace, then continues to extract characters so long as they form a valid part of an integer.
1
2
int foo;
ss >> foo;


On the other hand, this will first skip any whitespace, them consider any subsequent characters as a valid part of a string until the next whitespace (or end of stream) is encountered.
1
2
string s;
ss >> s;


Still, the original question said each part was separated by a space. So you could have done something like this:
ss << 100 << ' ' << 'f' << ' ' << "hello" << ' ' << 200;

OK thanks. Your right about the question anyway. But out of interest in my example why does it stop when it encounters the char f but does not stop when it encounters the int 200?
I tried to explain previously.
'f' is not part of a valid integer so extraction stops there.
'2' is a valid character which can be part of a string, so extraction does not stop.
Thanks Chevril. So everything in the stringstream is stored as a char and it all depends on the type of extraction?
Last edited on
That's right. A stringsteam behaves in many ways just like a disk file, or like an ordinary cin / cout. That's because they are all types of stream with similar characteristics.
Topic archived. No new replies allowed.