I'm using Dev C++ to create a program. I am familiar with fopen(), fscanf() and fprintf(). Using fscanf() i can get values, strings and such, but not white spaces. How can i get the file char by char, including spaces, tabs and new lines?
Using c++, how do you read a file character by character?
fgetc()
Reply:getchar()
Reply:ok, you need to use your fsreams to get the job done.
Ex:
#include %26lt;iostream%26gt;
#include %26lt;fstream%26gt;
#include %26lt;string%26gt;
using namespace std;
int main()
{
string fileline; //the string where the text from the file is being stored
ofstream File ("NewFile.txt"); //opens the file to be read
File.close();
//*opens and close NewFile.txt, we'll be putting our code in between these functions
//*This code will read the file and place it on the screen
//*There is no need to edit this code
ifstream SecondFile ("NewFile.txt");
while(! SecondFile.eof() ) //this while loop gets the text from the file line by line
{
getline(SecondFile, fileline); //get the line and put it in the fileline
cout %26lt;%26lt; fileline %26lt;%26lt; endl; //write the fileline onto the screen
}
SecondFile.close(); //ALWAYS CLOSE THE FILE
system("PAUSE");
}
Reply:Look into cin.getline(), cin.getchar(). Those will allow you to get a line until you hit a specific character (usually the \n, but you can specify which character) and put it into a char variable. It will also grab white space.
Reply:Since you are talking about the c libraries (cstdio in C++, stdio.h in C use the functions you mentioned) you can use fgetc, getc, or fread. You will find them discussed in the Dev-C++documentation and I'll link to the pages on cplusplus.com -but my keyboard is acting up and I'm tired so I don't DARE try to offer an example.
I'd go with fread to minimize the chance of skipping over whitespace characters.
Reply:fgetc()
Look into cin.getline(), cin.getchar(). Those will allow you to get a line until you hit a specific character (usually the \n, but you can specify which character) and put it into a char variable. It will also grab white space.
getchar()
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment