0

For scanning a complete line from a file in c++:

when I am using inFile >> s; where s is a string and inFile is an external file, it is just reading the first first word from the line.

Full code: (I am just trying to scan the file line by line and print the length of lines. )

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main()
{
ifstream inFile;
inFile.open("sample.txt");
long long i,t,n,j,l;
inFile >> t;
for(i=1;i<=t;i++)
{
    inFile >> n;
    string s[n];
    for(j=0;j<n;j++)
    {
        getline(inFile,s[j]);
        l=s[j].length();
        cout<<l<<"\n";
    }
}
return 0;
}

Sample.txt

2
3
ADAM
BOB
JOHNSON
2
A AB C
DEF

First integer is test case followed by no of words to come.

Sardar Usama
  • 18,585
  • 9
  • 33
  • 54
Saurabh Shubham
  • 43
  • 1
  • 12

1 Answers1

1

Use the std::getline function; it was made for this exact purpose. You can read about it here. In your specific case, the code would be:

string s;
getline(infile, s);
// s now has the first line in the file. 

To scan the complete file, you can put the getline() in a while loop since it returns false at the end of file (or if a bad bit is read). Thus you could do:

#include <iostream>
#include <fstream>
#include <string>

using namespace std;    

int main() {
    ifstream inFile;
    inFile.open("sample.txt");
    int lineNum = 0;
    string s;
    while(getline(infile, s) {
        cout << "The length of line number " << lineNum << " is: " << s.length() << endl;
    }
    return 0;
}
gowrath
  • 2,676
  • 2
  • 14
  • 29
  • But if there is integer to be scanned we have to mix '>>' with 'std::getline' na?? – Saurabh Shubham Aug 28 '16 at 10:05
  • @SaurabhShubham After you use getline() to get the line into string s, you can use a string stream to split it up using the stream extraction operators (">>"). [Here](http://stackoverflow.com/questions/20594520/what-exactly-does-stringstream-do) is an example – gowrath Aug 28 '16 at 10:09