Using file stream

Hi all,

I wrote this little piece of code in order to read the content of a text file. I expected to see the variable "test" equal to the whole first line of the file. Instead, the variable got the value of he first word only. How could I get the whole line?

Here is the content of my test file(quotes for clarification):
"This is a test.
This is only the second line!"

The output I expected: "This is a test."

The output I had: "This"

My code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include "stdafx.h"
#include <time.h>
#include <limits.h>
//ULLONG_MAX
#include <cstdlib>
#include <iostream>
#include <stdio.h>
#include <math.h>
#include <windows.h>
#include <fstream>
#include "math.h"
#include <vector>
#include <string>

ifstream in("C:\\my_file.txt", ios_base::in);

int main()
{
	string test;
	in >> test;
	cout << test;
	return 0;
}
Last edited on
Hey! std::cin stops reading at a white space, if you want to read an entire line, use std::getline

http://www.cplusplus.com/reference/string/string/getline/
Last edited on
Thanks for the fast reply!

Aparently I have some problem by using this command (getline) after using the operator ">>" with the same file stream.

In this case the getline() returns an empty string.

Is it possible to use both the operator ">>" and getline? This would be very helpful.

It would be easier to help you if you could provide your new code where you used getline, and a sample of what your textfiles looks like.
Here is the code I am using now. After line 9 I still have the console empty. The debug also shows the string "linha" empty after line 8.

This is the file content now:
"4
2
he loves to eat baguettes
il aime manger des baguettes"


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
void case_solve()
{
	int R,i;
	string linha;
	vector<string> vet;
	vector<vector<string>> w;
	in >> R;
	getline(in, linha);
	cout << linha;
}
int _tmain(int argc, _TCHAR* argv[])
{

	int i, cases;
	in >> cases;
	for (i = 1; i <= cases; i++)
	{
		case_solve();
	}
}
Topic archived. No new replies allowed.