Cannot get my get() to work c++

Hello,
I have read all of the references and forum questions on the get() function and basically i need to read an input from a file char by char and then there are a series of if statements of what to do with each char. A typical input would be 2+2 or 3*3.

Here is some of my code:


#include <iostream>
#include "Stack.h"
#include "link.h"
#include <fstream>
#include <cstdlib>

using namespace std;



int main()
{
string infix;
int newc, topc, popped;
Stack s;

cout << "Enter the infix to be converted: " << endl;
cin >> infix;

//read input to a file
ofstream outfile;
outfile.open("input.cpp");
outfile << infix;
outfile.close();


//read from the file outfile
ifstream infile;
infile.open("input.cpp");
while(!infile.eof()){

newc = infile.get();
if(){}
if else(){}
...

I do not think the get() is working like I mean for it to work.

My output says Run Failed exit value 1
Last edited on
i need to read an input from a file char by char

What makes you think it is not working?

Why is newc an int and not a char?


why do you write the input to a file and then try to read it again?
A better way to read the file char by char is this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <fstream>
#include <cstdlib>

int main()
{
  std::ifstream src(__FILE__);
  if (!src)
  {
    perror(nullptr);
    return -1;
  }
  char ch = 0;
  while((ch = src.get()) != EOF)
  {
    std::cout << ch;
  }

  return 0;
}
Thank you. I made newc a char and saved the input to a string. Then I converted the string into a char array and used a for loop to access each item in the array!
I made newc a char and saved the input to a string.

What kind of string a C-string or C++ string? If a C-string did you properly terminate the array to actually make a C-string?

Then I converted the string into a char array and used a for loop to access each item in the array!

Why convert it to a char array? A string, no matter if a C-string or a C++ string is basically an array of char already.

Topic archived. No new replies allowed.