简体   繁体   中英

How can I read keyboard input to character strings? (C++)

getc (stdin) reads keyboard input to integers, but what if I want to read keyboard input to character strings?

#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);}
}

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

Eg

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++.

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...

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM