views:

1411

answers:

4
#include "stdafx.h"
#include "string.h"
#include "stdio.h"
void CharReadWrite(FILE *fin);
FILE *fptr2;

int _tmain(int argc, _TCHAR* argv[])
{   

    char alpha= getc(stdin);
    char filename=alpha;
    if (fopen_s( &fptr2, filename, "r" ) != 0 )
      printf( "File stream %s was not opened\n", filename );
    else
     printf( "The file %s was opened\n", filename );
   CharReadWrite(fptr2);
   fclose(fptr2);
   return 0;
}
void CharReadWrite(FILE *fin){
    int c;
    while ((c=fgetc(fin)) !=EOF) {
        putchar(c);}
}
+1  A: 

A character (ASCII) is just an unsigned 8 bit integral value, ie. it can have a value between 0-255. If you have a look at an ASCII table you can see how the integer values map to characters. But in general you can just jump between the types, ie:

int chInt = getc(stdin);
char ch = chInt;

// more simple
char ch = getc(stdin);

// to be explicit
char ch = static_cast<char>(getc(stdin));

Edit: If you are set on using getc to read in the file name, you could do the following:

char buf[255];
int c;
int i=0;
while (1)
{
 c = getc(stdin);
 if ( c=='\n' || c==EOF )
  break;
 buf[i++] = c;
}
buf[i] = 0;

This is a pretty low level way of reading character inputs, the other responses give higher level/safer methods, but again if you're set on getc...

DeusAduro
getc returns an `int` for a reason. `EOF` will not generally fit in a `char`.
Logan Capaldo
would you take a look at the above code? I always get error messages when I tried to compile them
good point, so to be safe verify that the return value is not EOF, before casting to a char.
DeusAduro
Thanks Deus, but i don't think the bug is with my CharReadWrite function. I've commented out the portion, but i get error C2664: 'fopen_s' : cannot convert parameter 2 from 'char' to 'const char *'
+1  A: 

http://www.cplusplus.com/reference/iostream/istream/getline/ Ta da!

ryansstack
im writing in C++ not C....
Now that his code is posted, this is definitely the way to go.
DeusAduro
Do you mean C not C++, because getline is a C++ function.
DeusAduro
+2  A: 

Continuing with the theme of getc you can use fgets to read a line of input into a character buffer.

E.g.

char buffer[1024];
char *line = fgets(buffer, sizeof(buffer), stdin);
if( !line ) {
  if( feof(stdin) ) {
      printf("end of file\n");
  } else if( ferror(stdin) ) {
      printf("An error occurerd\n");
      exit(0);
  }
} else {
  printf("You entered: %s", line);
}

Note that ryansstack's answer is a much better, easier and safer solution given you are using C++.

Logan Capaldo
A: 

Since you already are mixing "C" code with "C++" by using printf, why not continue and use scanf scanf("%s", &mystring); in order to read and format it all nicely ?

Or of course what already was said.. getline

Milan