简体   繁体   English

如何阅读键盘输入的字符串? (C ++)

[英]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? getc(stdin)将键盘输入读取为整数,但是如果我想将键盘输入读取为字符串怎么办?

#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. 继续使用getc的主题,您可以使用fgets将输入行读入字符缓冲区。

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++. 请注意,鉴于您正在使用C ++,ryansstack的答案是一个更好,更简单,更安全的解决方案。

A character (ASCII) is just an unsigned 8 bit integral value, ie. 字符(ASCII)只是一个无符号的8位整数值,即。 it can have a value between 0-255. 它的值可以在0-255之间。 If you have a look at an ASCII table you can see how the integer values map to characters. 如果您查看ASCII表,则可以看到整数值如何映射到字符。 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: 编辑:如果您设置使用getc读取文件名,则可以执行以下操作:

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... 这是读取字符输入的一种非常低级的方式,其他响应则提供了较高级/更安全的方法,但是如果您在getc上进行了设置,则同样会...

Since you already are mixing "C" code with "C++" by using printf, why not continue and use scanf scanf("%s", &mystring); 由于您已经通过使用printf将“ C”代码与“ C ++”混合在一起,为什么不继续并使用scanf scanf("%s", &mystring); in order to read and format it all nicely ? 为了很好地阅读和格式化所有内容?

Or of course what already was said.. getline 或当然已经说了.. getline

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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