How can I make my program read a line from a file. I don't want it to stop on spaces, I want it to read the whole line.
Printable View
How can I make my program read a line from a file. I don't want it to stop on spaces, I want it to read the whole line.
use getline()
for character arrays:std::cin.getline(char*,size,delim)
for Strings:getline(std::cin,string,delim)
examples:
Code:char linech[20];
std::string linestr;
std::cin.getline(linech,20,'\n');
getline(std::cin,linestr,'\n');
Wow, I think this will be the first time I found something useful from MSDN that actually deals with standard code
http://msdn.microsoft.com/library/de...estlsample.asp
and here is the code sample, this uses the C++ standard String class by the way.
Code:#include <string>
#include <iostream>
using namespace std ;
int main()
{
string s1;
cout << "Enter a sentence (use <space> as the delimiter): ";
getline(cin,s1, ' ');
cout << "You entered: " << s1 << endl;
}
basically, if you get rid of the third parameter (the ' ') then it will continue until it reaches a newline by default. such as the example below
EDIT: Darn, beaten to it.Code:#include <string>
#include <iostream>
using namespace std ;
int main()
{
string s1;
cout << "Enter a sentence: ";
getline(cin,s1);
cout << "You entered: " << s1 << endl;
}
Well I said "from a file", so...
I thought this is problem is because I don't know how to use fgets, but:
A part of my code. It doesn't read correctly, all pieces of hello are filled with the last line...Code:while(fgets(run,100,pFile)){
hello[ib]=run;
ib=ib+1;
}
for(int i=0;i<7;i++){
cout<<"begin\n"<<ib<<hello[i]<<"\nend"<<endl;
}
the getline example I used is usable with filestreams as well, just replace cin with the filestream
EDIT
Ok, I threw together a little demo of what I mean
Yes, I know, the filename is hardcoded, but it worked to test withCode:#include <fstream>
#include <iostream>
#include <string>
using namespace std;
int main()
{
string InputBuffer;
fstream InputFile;
InputFile.open("testfile.txt", fstream::in);
while(!InputFile.eof())
{
getline(InputFile,InputBuffer);
cout << "Got one line: " << InputBuffer << endl;
}
InputFile.close();
cout << endl << "All lines read and printed" << endl;
}
string version of getline:Quote:
Originally Posted by maxorator
getline takes a reference to an istream as its first parameter. It can be anything that can be reduced to an istream. ifstreams, iostreams, istringstream, etc all derive from istream which means they can all be used as the first parameter. Also on many systems your input and output are files.
io version of getline:
anything that inherits from istream also inherits the member function getline. So see above